Bind ng-model name and ng-click inside ng-repeat in angularjs - angularjs

I need to know naming convention for the ng-model and ng-click inside the ng-repeat. And also need to know how to use each model name and ng-click function in the controller. I have given a sample code to show you what I exactly need know.
<input name="" type="button" ng-click="incrementRoomCount()">
<div ng-repeat="student in studentList">
<div>Room <span>{{student.studentCount}}</span></div>
<div>
<input name="" type="button" ng-click="removeStudent()">
<input name="adult" type="text" ng-model="noOfStudents">
<input name="" type="button" class="roomPopupPlusBtn" ng-click="addStudent()">
</div>
<div ng-repeat="studentAge in studentList">
<div ng-show="studentAgeWrapper">
<select name="age">
<option ng-repeat="studentAge in ['20','21','22','23','24','25']">{{studentAge}</option>
</select>
</div>
</div>
</div>
Thanks

The following fiddle demonstrates how to call functions when repeating over items. You could also just pass in an id to the remove function.
<input value="Remove From Room" type="button" ng-click="removeStudent(student)"/>
</div>
$scope.removeStudent = function(student) {
angular.forEach($scope.studentList, function(checkStudent, index) {
if (checkStudent.id === student.id) {
$scope.studentList.splice(index,1);
}
});
};
http://jsfiddle.net/houston88/ab23r/1/

Related

How to dynamically validation under ng-repeat in angularjs

Hello I am beginner of Angularjs and I want to build dynamic validations.Here is my code shortened as well as possible.
JS
$scope.inputValidates = [
{ 'name':'name',
'validate':'required',
},
{ 'name':'email',
'validate':'type = email',
}]
HTML
<div ng-repeat="vitem in vm.inputValidates">
<input name={{vitem.name}} ng-model="vm.useraccount[vitem.name]" {{item.validate}}>
</div>
I want this input result as
<input name=name ng-model="vm.useraccount[vitem.name] required>
<input name=name ng-model="vm.useraccount[vitem.name] type = email>
Thanks for taking time for this.
Use ng-required:
<div ng-repeat="vitem in vm.inputValidates">
<input name={{vitem.name}} ng-model="vm.useraccount[vitem.name]" ng-required="item.validate">
</div>
By the way, I see you assigned inputValidates to your $scope. So you should be accessing it in your view by inputValidates, not vm.inputValidates.
Sample is HERE
Sample contains both required and pattern validation applied on textbox rendered using ng-repeat and use ng-switch based on your validation type
<div ng-repeat="field in fields">
<div style="width:600px">
<div ng-form name="validMe" style="width:58%;float:left" ng-switch="field.validationType">
{{field.name}} :
<div ng-switch-when="required">
<input id="input{{$index}}" name="input{{$index}}" type="text" ng-model="field.value" required>
<span style="color: #a94442" ng-show="validMe['input\{\{$index\}\}'].$error.required ">Field Required!</span>
</div>
<div ng-switch-when="email">
<input type="email" id="input{{$index}}" name="input{{$index}}" ng-model="field.value" ng-pattern="/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/">
<span style="color: #a94442" ng-show="validMe['input\{\{$index\}\}'].$error.pattern">Not a valid email!</span>
</div>
</div>
</div>
</div>

How to use one model in ng-repeat using AngularJs?

This is my Fiddle.
http://jsfiddle.net/0c5p38dt/1/
In the above fiddle use ng-model in textfield and add save button
<input type="text" ng-model="eachItem.value"/>
<input type="button" value="save" ng-click="save()"/>
and i write code in js file :-
$scope.save=function(){
console.log($scope.data);
};
In the above code first i click add button when i enter data in first textfield(name) that will also effect on second textfield(name). I want to save the data . So how to differentiate these textboxes.
you should use a 'name' attribute in your input fields with angular
$index
on ng-repeat.
in your Fiddle:
<div ng-app>
<div ng-controller="Ctrl">
<div ng-repeat="eachItem in data">
<input type="button" value="add" ng-click="addFields(eachItem)"/>
<label>{{eachItem.label}}</label>
<input type="text" name="eachItem.label[$index]" />
</div>
</div>
</div>
The result would be like:
<input type="text" name="email[1]">
<input type="text" name="email[2]">
<input type="text" name="email[3]">
<input type="text" name="name[1]">
<input type="text" name="name[2]">
I'm not completely sure what you want, but I don't think you want the <input> in an ng-repeat, maybe what you want is in your .html:
<div ng-app>
<div ng-controller="Ctrl">
<label>Name</label>
<input type="text"ng-model="item.name"/>
<label>Email</label>
<input type="text"ng-model="item.email"/>
<input type="button" value="add" ng-click="addFields(item)"/>
<div ng-repeat="item in data">
<div ng-bind="item.name"></div>
<div ng-bind="item.email"></div>
</div>
</div>
</div>
and in your .js:
function Ctrl($scope) {
$scope.data=[];
$scope.addFields = function (item) {
$scope.data.push(item);
};
}
This will give you the inputs once and then keep track (and display) the data from the inputs

Click All submit buttons from a ng-repeat form

I have an angularjs ng-repeat form using MEAN stack, where i have an external button outside the ng-repeat to trigger all the ng-repeat form. but doing so it submits only the first ng-repeat form. all the others are not submitted. how should i submit all forms with one click.
HTML
<div class="ui-widget-content">
<ol class="minheight650">
<div class="overflow-y-scroll">
<div ng-repeat="item in subfoodss track by $index | filter:categoryfilter | filter:typefilter | filter:searchallfood">
<li ng-show="item.name" >
<div class="col-md-4">
<form name="subfoodForm" id="subfoodform" data-ng-submit="addSubfood()" >
<input type="text" data-ng-model="sbody" name="sbody" id="sbody" class="form-control" placeholder="Your Subfood" required disabled>
<input type="text" data-ng-model="sprice" name="sprice" id="sprice" class="form-control" placeholder="Your Subfood" required disabled>
<md-select data-ng-model="sqty" id="sqty" required>
<md-option value="1" selected>1</md-option>
<md-option value="2">2</md-option>
<md-option value="3">3</md-option>
</md-select>
<div class="col-md-3 ">
<input type="checkbox" >
</div>
<input type="submit" ng-click="secondFx()" id="btnTwo" value="Subfood">
</form>
</div>
</li>
</div>
</div>
<div>
<md-switch class="md-primary" ng-click="doSomething()" id="selecctall">
<h4>Confirm All</h4>
</md-switch>
</div>
</ol>
</div>
AngularJS Controller
$scope.secondFx = function() {
angular.element('#btnTwo').click();
};
$scope.doSomething = function() {
$scope.secondFx();
};
Reference elements in a controller isn't a good idea (separation of concern) so don't do angular.element('#btnTwo').click();
I think the best solution is to create a directive which will submit all child forms. This directive could be added to the selecctall button, and react on click.
Is that ok for you ?

Cannot read property '$valid' of undefined

I have a form with a name field and two validations - required and max-length.
When I enter correct value, the form in controller is showing valid and returning true. But on entering wrong data, $valid is not throwing false and simply says -
Cannot read property '$valid' of undefined
Why is the form getting undefined in this case?
Jsfiddle here
Thanks in advance
Add ng-submit attribute to the form:
<form name="myForm" ng-submit="SaveAndNext()" novalidate>
Change controller to:
function myCtrl($scope, $log){
$scope.data = {};
$scope.SaveAndNext = function(){
if($scope.myForm.$valid){
$log.info('Form is valid');
$log.info($scope.data);
} else {
$log.error('Form is not valid');
}
}
}
Remove ng-click event handler from your submit button
Updated fiddle: http://jsfiddle.net/9cgopo7d/1/
I included the $log service because it's a useful default service and you might not know about it.
See demo below pass your form to controller with the submit click
ng-click="SaveAndNext(myForm)"
and now you can easy access all your form properties
function myCtrl($scope) {
$scope.SaveAndNext = function(form) {
console.log(form);
if (form.$valid) {
alert(form.$valid);
} else {
alert("!" + form.$valid)
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="registrationdetails" ng-app="" ng-controller="myCtrl">
<form name="myForm" novalidate>
<div class="list">
<div class="item list-item">
<div class="row row-center">
<div class="col-50"> <span class="form-field-name">Name</span>
</div>
<div class="col-50">
<textarea type="text" rows="5" ng-model="data.Name" name="Name" ng-maxlength=45 required></textarea> <span ng-show="myForm.Name.$dirty && myForm.Name.$invalid">
<span class="form-error" ng-show="myForm.Name.$error.required">Name is required</span>
<span class="form-error" ng-show="myForm.Name.$error.maxlength">Name should be max 45 characters</span>
</span>
</div>
</div>
</div>
<div class="item list-item">
<div class="row row-center">
<div class="col-50"> <span class="form-field-name">Type</span>
</div>
<div class="col-50">
<select ng-class="{defaultoption: !data.Type}" ng-model="data.Type" name="Type" required>
<option value="" disabled selected class="defaultoption">Type</option>
<option value="1" class="actualoption">Type 1</option>
<option value="2" class="actualoption">Type 2</option>
</select>
<span ng-show="myForm.Type.$dirty && myForm.Type.$invalid">
<span class="form-error" ng-show="myForm.Type.$error.required">Type is required</span>
</span>
</div>
</div>
</div>
<div class="item list-item">
<div class="row">
<div class="col">
<input type="submit" class="button" ng-click="SaveAndNext(myForm)" value="Next">
</div>
</div>
</div>
</div>
</form>
</div>
Place $scope.data={}; at the top of controller:-)
This is happening becuase you are directly submit the form which doesn't yet initialized the data object and therefore name data.Name is not recognized.
And if you place $scope.data={} in that case we have empty data object initialized.So in second case we have atleast reference of empty object whereas in first case it doesn't have any reference.
Fiddle
HTML:
<form name="form" id='form' novalidate>
<input type="text"required name="Title" ng-model="Title">
<div ng-messages="form.Title.$error">
<div ng-message="required">Field Required</div>
</div>
</form>
JS:
$scope.save= function(){
if (!scope.createMessage.$valid) {
scope.form.$submitted = true;
return;
}
The format for using $valid should be like this. If you don't get again then visit the official site of AngularJs.
I had similar problem, but in my case I was a ng-if creating a child scope that did not have the form defined.
Just changed the ng-if to ng-show and the form stop be undefined.

Issue with ng-model and ng-repeat, duplicate forms

I have a page where multiple forms are created based on ng-repeat. Everything works fine until write something into the input and everything gets duplicated on all the other repeated forms input elements. I have used ng-model="Notify.message" which is nothing but object which takes the value from the input and sends to control on button submit and hence rest of the logic.
I am looking for when if one form is been filled, other forms should keep quite and shouldn't duplicate the values written in input text of form 1.
Here is the code:
<div data-ng-show="alluserposts.length > 0">
<div id="b{{userpost.id}}" data-ng-repeat="userpost in alluserposts" >
<div class="row" style="margin-left: -5px">
<form class="text-center" role="form" id=f1{{userpost.id}} name="userForm"
ng-submit="notify(userForm.$valid, userpost, apiMe)" novalidate>
<div class="row">
<div class="col-xs-8 col-md-4">
<div class="form-group">
<input data-container="body" data-toggle="popover" data-placement="top"
data-content="Any message which you would like to convey to post owner"
type="text" ng-model="Notify.message" data-ng-init="Notify.message=''"
id="u{{userpost.id}}"
placeholder="Enter a Message or Phone number" class="form-control"
required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">It is
required.</p>
<script>$(function () {
$("[data-toggle='popover']").popover();
});
</script>
<input type="hidden" ng-model="Notify.loggedInEmail"
ng-init="Notify.loggedInEmail = result.email"/>
<input type="hidden" ng-model="Notify.postId" ng-init="Notify.postId = userpost.id"/>
<input type="hidden" ng-model="Notify.destEmail"
ng-init="Notify.destEmail = userpost.userEmail"/>
</div>
</div>
<div ng-show="loginStatus.status == 'connected'" class="col-xs-4 col-md-2">
<button class="btn btn-primary" ng-disabled="userForm.$invalid || !userForm.$dirty"
type="submit">
Notify Post Owner
</button>
</div>
</div>
</form>
</p>
</div>
</div>
</div>
</div>
Issue fiddle - jsfiddle
Here you can when something is written in one input, other gets filled too :( . Also Notify is a Java mapped object and message is a variable inside it. Pls let me know how can this can be segragated!
You bind all of your inputs to same variable on $scope.
You must bind every text box to a distinct variable on $scope:
View:
<ul ng-repeat="post in posts">
<li>{{$index}}
<input type="text" ng-model="emails[$index]"/>
</li>
</ul>
Controller:
$scope.emails = [];
I am also at the starting phase of angularjs.
I have faced the same issue few days ago and resolved it by providing dynamic model name in ng-model like
<input type="text" ng-model="Notify[post.userEmail]" ng-init="Notify[post.userEmail] = post.userEmail" />
Working fiddle: Fiddle

Resources