I am new to Angular. Please, consider the following piece of code.
<form name="newEventForm">
<fieldset>
<label for="eventName">Event Name:</label>
<input id="eventName" required ng-model="event.name" type="text" placeholder="Name of your event...">
<button ng-click="saveEvent(event, newEventForm)" type="submit" class="btn btn-primary">Save</button>
<button ng-click="cancelEdit()" type="button" class="btn btn-default">Cancel</button>
</form>
My question is - why do we need to pass the event argument to the saveEvent function? Doesn't using ng-model auto generate an event.name variable through two-way binding on the Angular side? e.g.
<form name="newEventForm">
<fieldset>
<label for="eventName">Event Name:</label>
<input id="eventName" required ng-model="event.name" type="text" placeholder="Name of your event...">
<button ng-click="saveEvent( newEventForm)" type="submit" class="btn btn-primary">Save</button>
<button ng-click="cancelEdit()" type="button" class="btn btn-default">Cancel</button>
</form>
In this second version of the code, I am not explicitly injecting event as a function parameter. However, when pressing submit, this is the code for saveEvent
$scope.saveEvent = function(newEventForm)
{
alert(1);
alert(newEventForm.$valid);
if(newEventForm.$valid)
{
window.alert('event ' + event.name + ' saved!');
}
}
and event is undefined. Shouldn't it be defined? Apologies if the question is a newbie's question. Just trying to get my head around how scope items are created through ng-model, and how does two-way binding work. Thanks !
UPDATE
Doh, I should've used $scope.event. Then it works. Thanks, like I said - new to this and it only dawned to me after I asked the question :)
The view is creating the event variable under the associated scope, use $scope.event.name.
Good luck
Actually all variable or model which are specified in the html are scope variable.
Example
<div ng-controller="myController" ng-init="name='Hello World'">
{{name}}
<button ng-click="myFn(name)"> Click Me </button>
</div>
In this example, I have initiated a variable called name. It is actually a scope variable. This code will actually like
myApp.controller("myController", function($scope){
$scope.name = "Hello World";
$scope.myFn = function(param){
// here you can see that your variable name passed from html is same as your scope variable
if(param == $scope.name){
alert("Yes, two are equal !!!");
}
}
});
This two are same. You can either use html or js.
Related
i cant push id to an object for each row with formbuilder.
So this is my form
<form [formGroup]="add">
<label for="name"> Name:
<input id="name" type="text" formControlName="name">
</label>
<label for="email"> E-Mail:
<input id="email" type="email" formControlName="email">
</label>
<button class="btn btn-primary" type="submit" (click)="onSubmit(add.value)">add
</button>
</form>
my row
<tr *ngFor="let person of persons; let i = index; ">
<td>{{person.id}}</td>
<td>{{person.name}}</td>
<td>{{person.email}}</td>
<button class="btn btn-primary" type="submit" (click)="deleteUser(i)">d
</button>
</tr>
and i'm pushing my object to array like this way
onSubmit(value) {
this.addToUsers(value);
}
addToUsers(person) {
this.persons.push(person);
}
So my question is, how to push unique id for each row to object and then show it in html with command {{person.id}}, within name and e-mail.
I'm using Angular 8.
Thanks in advance.
in onSubmit you can generate a unique id and assign it to the person object then call addToUsers and push it to array
In your form element, use the official ngSubmit binding if possible, here's the benefits as to why: https://angular.io/api/forms/NgForm
Sadly I think the only solution using template forms is to generate the ID. (see answer from Durgesh Pal)
But! A better solution to this would be to use ReactiveForms, they allow much more flexibility and you can directly identify the objects within the form (as you can literally use this.form.value and it'll give you an object of the current form back) - as well as generate forms from scratch purely via RxForm code. So I'd just like to suggest have a look at this too: https://angular.io/guide/reactive-forms
Hopefully this is helpful
Generate unique id using random function or date.
addToUsers(person) {
person = JSON.parse(JSON.stringify(person));
person.id = new Date().getTime();
this.persons.push(person);
}
I have repeated a div by using angular js ng-repeat
<div ng-repeat="exampleData in example">
<input type="text" id="{{ $index }}percentage"/>
<button type="btn btn-success" ng-click="submitted('{{ $index }}fromHours')">Submit</button>
</div>
So, when I click on submit button submitted method will be called with input feilds id passed as parameter in it,
Please take a look at the js code below :
$scope.submitted = function(percentage){
console.log($('#'+percentage).val());
}
Now when I use the parameter and print its value I'm getting error, Saying
Syntax error, unrecognized expression: #{{ $index }}percentage
How should I get the exact value of the input type with {{ $index }}percentage as ID
I have written $index to have the unique id as the text box will be repeated many times.
Please help, thanks in advance :)
remove the expressions when you pass an index to a ng-click function.
ng-click="submitted($index + 'fromHours')">
Try this
<input type="text" ng-id="$index + 'percentage'"/>
verify in the HTML if this value is properly populated.
Same is applicable to button as well
<button type="btn btn-success" ng-click="submitted($index + 'fromHours')">
<input type="text" ng-id="$index + 'percentage'"/>
<button type="btn btn-success" ng-click="submitted('$index + 'fromHours')">Submit</button>
Do it this way.
I try to hide my form after it has been 'submitted'. I want to do it with ng-if. Clicking on the button 'See' displays the form on and off, but it does not work on the button 'Add'. What is the reason for that?
I have created a JSFiddle. Link to JSFiddle.
My Form:
<form name="userAddForm" ng-submit="something()" class="form-horizontal" role="form">
<div class="form-group">
<label class="col-md-2 control-label">Username</label>
<div class="col-md-3">
<input name="username" ng-model="user.username" class="form-control" ng-required="true" placeholder="Username" type="text" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Password</label>
<div class="col-md-3">
<input name="password" ng-model="user.password" class="form-control" placeholder="Password" type="password" ng-required="true" />
</div>
</div>
<button ng-disabled="userAddForm.$invalid" type="submit" ng-click="add=!add" class="btn btn-success">
<span class="glyphicon glyphicon-ok"></span> Add
</button>
</form>
</div>
Please, don't use $parent!
Use proper prototypal inheritance.
The reason it doesn't work is because you are creating a new scope through the usage of ngIf.
It does not create an isolate scope so you don't have to worry about that.
When you pass a primitive, Javascript will "shadow" that value on the prototype of the new scope.
As such, it is no longer a direct reference to the value in your parent scope.
How do you get around that?
add a dot
That roughly translates into; use an object and bind to a property of that object. objects don't get shadowed as they are not a primitive. you get to keep the reference and it just works™.
jsfiddle
Every directive in angularjs create different level of scope.So,there is different level of scope, one at form tag and one at button inside the form which create parent and child relationship between form and button inside it.As add is,primitive variable,its changes in child is not reflected in parent scope.
So,either use $parent service or define thet add variable in following way.
$scope.objHidShow = {};
$scope.objHidShow.add= false;
I would do it by calling a controller function:
$scope.something = function() {
$scope.shown = !$scope.shown;
}
What I did is to define that function and I made your controller working for the complete form.
https://jsfiddle.net/udc2rjrn/2/
The ng-if directive creates a new scope so you need to use $parent:
<button ng-disabled="userAddForm.$invalid" type="button" ng-click="$parent.add=!$parent.add" class="btn btn-success">
Updated JSFiddle
I've created a simple form with a name:
<form novalidate ng-controller="TestController" role="form" name="testForm">
<input type="number" min="10" name="textForm" value="4">
<input type="submit" ng-click="validate(testForm)">
</form>
and then I've created a controller:
angular.module("testModule", []).controller("TestController", function($scope){
$scope.validate = function(form){
alert("inside the function validate()");
}
});
This works correctly (since the alert pop up on screen) as you can see here.
Now I've added a variable to the scope $scope.testNumber = 5; and appended this version to the form's name name="testForm{{testNumber}}">and do the same thing on the input submit of the form <input type="submit" ng-click="validate(testForm{{testNumber}})">. And this doesn't work, since I can't see any alert, as you can see here. The syntax is not correct, but how can achieve what I want to do?
Since your ng-click is a function with a param, you need to concat the variables. So testForm + testnumber should give you the desired result.
Controller
angular.module("testModule", []).controller("TestController", function($scope){
$scope.testNumber = 5;
$scope.validate = function(form){
alert("inside the function validate()" + form);
}
});
Html
<form novalidate ng-controller="TestController" role="form" name="testForm{{testNumber}}">
<input type="number" min="10" name="textForm" value="4">
<input type="submit" ng-click="validate(testForm + testNumber)">
</form>
And a plunker to demo the changes
When you use the name attribute of the form element, you are publishing the form instance into the controller scope.
Thus, you will have a property testForm which you can access with $scope.testForm. (Documentation)
Strictly speaking, you don't have to pass the form to the function that you call when you submit as it is accessible from the scope.
However, if you do wish to carry it out, I suggest that you separate the code from the markup - define a scope property in your controller that will hold the name of the form like so:
$scope.myForm = 'testForm1';
You can then use this in your markup as:
<form name="{{myForm}}">
...
<input type="submit" data-ng-click="validate(myForm)"/>
</form>
You can easily create an array of form names and use them in your markup (by indexing them) without having to do string concatenation and cluttering your markup.
I have two controllers in my AngularJS apps. In my first Controller, I have an input/dropdown field, which value I want to use in second nested controller for each ng-Change. For example,
My Code (HTML) ::
<body ng-app="myApp" ng-controller="DropdownCtrl">
<input type="text" class="form-control" ng-model="dt" ng-change="changeDate(dt)" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
<div class="row" ng-controller="MainCtrl">
<!-- other code -->
</div>
</body>
Now what I want to do, when ng-Change is happening, I want to use changeDate(dt) function's value in MainCtrl
In order for a parent controller to communicate with a child controller, the parent controller should use $scope.$broadcast('changedValue', dt);
This will broadcast to all children controllers the new value of dt. The childController should then listen for the change with the following code:
$scope.$on('parent-message', function (event, dt) {
//you can now use dt in the child controller to do whatever it is you wanted
});
This is especially nice when using routeProviders and ng-view
Here is a great tutorial that explains this all really well: