ng-model in ng-repeat - how to send values to server - angularjs

im using ng-repeat to create dynamic number of textboxs.
<div class="orgevent" ng-repeat="i in getNumber(numOfEvents) track by $index">
<input class="dest" type="text" value="Free text" ng-model="i.freeText">
</div>
i want (on click) to take the values that the user write in the textBox and send it to the server,
how can i do it?
i tried to take it in the JS by ng-model but the value is always "undefined"

You can use ng-model as array and read it on click. Take a look
http://jsfiddle.net/ucskyv67/74/
app.controller("cookieCtrl", function ($scope, $cookies) {
$scope.numbers= [1,2,3,4,5,6];
$scope.userVals=[];
$scope.getVal= function(){
console.log($scope.userVals);
}
});
<div ng-app="cookieApp" ng-controller="cookieCtrl">
<div class="orgevent" ng-repeat="i in numbers track by $index">
<input class="dest" type="text" value="Free text" ng-model="userVals[$index]">
</div>
<button ng-click="getVal()">Read</button>
</div>

one option is to add ng-change to your input and implement a method in your controller to call the server-
<input ng-change="handleChange(i.freeText)" class="dest" type="text" value="Free text" ng-model="i.freeText">

Related

Can ng-model replace Ids?

Is there a way to avoid IDs while creating elements i.e. using ng-model it is easier to validate form fields and other stuff?
<div ng-repeat="x in TestData">
<input type="text" id="nameField-{{$index}}"/>
</div>
The above code will display the number of input boxes equal to the length of the TestData array where every text box will have a unique id "nameField-0", "nameField-1" and so on, using these IDs we can take the textbox values, validate the fields etc.
<div ng-repeat="x in TestData">
<input type="text" ng-model=""/> <!-- what shall be done here to have unique IDs -->
</div>
Although going with IDs is working fine for me but as far as I can understand If I use IDs then that will not be a pure angular way (or IDs cannot be replaced by mg-models), correct me If I am wrong.
You don't need to grab element with id/name/etc. You can use ng-model to bind your values and ng-pattern to validate them.
<div ng-repeat="x in testData">
<ng-form name="tForm">
<input type="text" name="tInput" ng-model="x.name" ng-pattern="/^[A-Z]*$/" />
<span ng-if="tForm.tInput.$error.pattern" style="color:red">Invalid!</span>
</ng-form>
</div>
See this jsbin.
In your controller add this,
$scope.nameField = [];
in ng-reapeat add this,
<div ng-repeat="x in TestData">
<input type="text" ng-model="nameField[$index]"/>
</div>
nameField will be an array with all your values.
<div ng-repeat="x in TestData" ng-init='this["nameField-"+x]'>
<input ng-model='this["nameField-"+x]'/>
</div>
You use ng-init to add new variables to the controller, "this" refer to your scope, and since the scope is an object, since this[bla] == this.bla tou are actually saying, add to my scope a variable name "nameField=" and you add the x value.
after you have created your variable, just use it in the same way in your ng-model.
If you want to show your variable's value in any div/span, just use it via ng-bind:
<div ng-bind='this["nameField-"+x]'></div>

'or', 'and' in ng-model angularjs

I have a list of items, some of them has property value, some has property default. And I need to bind it into the input[text] with ng-repeat.
Array is looks like:
$scope.arr = [
{value:'name'},
{value:'dog'},
{default:'cat'},
{value:'lastName'},
{default:'ring'}
];
And in html:
<div ng-repeat='item in arr'>
<input type='text' ng-model='item.value || item.default'>
</div>
It works, but I have error message in console "[ngModel:nonassign] http://errors.angularjs.org/1.5.8/ngModel/nonassign?p0=item.value%20%7C%7CNaNtem.default&p1=%3Cinput%20type%3D%22text%22%20ng-model%3D%item.value%20%7C%7C%item.default%22%20class%3D%22ng-pristine%20ng-untouched%20ng-valid%22%3E". Because ng-model doesn't work with expression..
Perhaps there is another way to solve it?
Plnkr example
You can do it this way:
<div ng-repeat='item in arr'>
<input type='text' ng-hide='item.default' ng-model='item.value'>
<input type='text' ng-show='item.default' ng-model='item.default'>
</div>
Plunker example.
You can try to create a second array, using only single type of object and bound it to the view.
Then, you can watch for changes and re-assign values to your original array.
It is more a MVVM approach (creating a "viewModel") that intermediate between the controller model and the view.
$scope.valueOrDefault = function (item){
return item.value|| item.default;
}
and HTML
<div ng-repeat='item in arr'>
<input type='text' ng-model='valueOrDefault(item)'>
</div>

How to repeat duplicate objects using ng-repeat in AngularJs?

This is my code.
$scope.data=[];
$scope.data=[{"label":"name","type":"string"},{"label":"email","type":"string"}];
$scope.addFields = function (field) {
$scope.data.push(field);
};
This is my html:-
<div ng-repeat="eachItem in data">
<input type="button" value="add" ng-click="addFields(eachItem)"/>
<label>{{eachItem.label}}</label>
<input type="text" ng-model="fieldValue"/>
</div>
when i click add button push one more object into $scope.data array like
$scope.data=[{"label":"name","type":"string"},{"label":"email","type":"string"},{"label":"name","type":"string"}];
In the above i got an error
angular.min.js:102 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.14/ngRepeat/dupes?p0=nestedField%20in%20fieā€¦%2C%22type%22%3A%22string%22%2C%22%24%24hashKey%22%3A%22object%3A355%22%7D
at Error (native)
I have duplicate objects after adding. because i want to repeat label names using ng-repeat in angularjs.First i have output like this
OutPut:-
name textbox
email textbox
After add button click Output:-
name textbox
email textbox
name textbox
use track by $index
var app = angular.module("app",[])
app.controller('ctrl',['$scope', function($scope){
$scope.data=[];
$scope.data=[{"label":"name","type":"string"},{"label":"email","type":"string"}];
$scope.addFields = function (field) {
$scope.data.push(field);
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div class="item item-checkbox">
<div ng-repeat="eachItem in data track by $index">
<input type="button" value="add" ng-click="addFields(eachItem)"/>
<label>{{eachItem.label}}</label>
<input type="text" />
</div>
</div>
Use track by for this purpose.
<div ng-repeat="eachItem in data track by $index">
<input type="button" value="add" ng-click="addFields(eachItem)"/>
<label>{{eachItem.label}}</label>
<input type="text" ng-model="eachItem.value" />
</div>
You also able to use track by with your custom filed, like id, or whatever
Important: It's better to use track by in each ng-repeat, cause it's improve ng-repeat's performance (read more).
But avoid to use track by in ng-options and other cases when you use select as .. for ... construction (read more)
JsFiddle here
You have to ensure that items in the array have an unique key. If that is not possible you can use track by $index in the ng-repeat.
Check the details here

AngularJS binding datatimepicker selected value to ng-model

I have a newbie AngularJS question - I am using a datetimepicker library and I'm having a hard time getting the date selected to bind to my model... I saw some posts talking about not being able to access the datetimepicker model directly, but in my case I find that if I just manually TYPE IN a text value in my date input box, it binds! If I select a date with the chooser, I get the dreaded 'undefined' :(... help?
HTML markup:
<div class="col-md-2">
<div name="fromDateTime" class="input-group date" id="datetimepickerFrom">
<input class="form-control" type="text" name="fromDateTime" ng-model="formEntries.fromDateTime"/>
<span class="input-group-addon" data-ng-click="pickFromDateTime()"><span class="glyphicon glyphicon-calendar" id="calIconFrom"></span></span>
</div>
</div>
<div class="col-md-2">
<div name="toDateTime" class="input-group date" id="datetimepickerTo">
<input class="form-control" type="text" name="toDateTime" ng-model="formEntries.toDateTime"/>
<span class="input-group-addon" data-ng-click="pickToDateTime()"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</div>
Controller:
$scope.pickFromDateTime = function () {
$("#datetimepickerFrom").datetimepicker();
$("#datetimepickerFrom").datetimepicker().change(function() {
$(this).data("DateTimePicker").hide();
console.log($(this).data("DateTimePicker").getDate());
});
}
$scope.pickToDateTime = function () {
$("#datetimepickerTo").datetimepicker();
$("#datetimepickerTo").datetimepicker().change(function() {
$(this).data("DateTimePicker").hide();
console.log($(this).data("DateTimePicker").getDate());
});
}
$scope.getData = function() {
console.log($scope.formEntries.fromDateTime);
console.log($scope.formEntries.toDateTime);
}
Never ever ever write DOM or jQuery code in your controller. It will never work properly. You must create a directive to do this. The directive will listen to events from whatever library you're using and update your model. Here is an example of a directive that happens to work with the datepicker. This should get you on the right track.

Reference the inputs created with ng-repeat in angular based on the number of variable options

The problem I'm facing, as outlined in the code, is that I can't seem to find out how to bind the second checkboxes (created with ng-repeat) to some model which I would then be able to use further down the code (showing/hiding yet another set of options). Also, I managed to show the additional number of inputs based on the count parameter in the $scope.availableOptions by using the $scope.getItterator function, but now I don't see how would I access the values of these checkboxes? I know I have to somehow use the option "ng-model" but am failing to do so, so any help appreciated.
My code is here, but am showing it here too:
html:
<div ng-controller='MyCtrl'>
Show additional options <input type="checkbox" ng-model="additionalOptions">
<div ng-show="additionalOptions">
<ul>
<li ng-repeat="option in availableOptions">
<label class="checkbox" for="opt_{{option.id}}">
<input type="checkbox" name="opt_{{option.id}}" id="opt_{{option.}}" />
{{option.name}}
<ul ng-show="if the upper checkbox is clicked">
<li>
<input type="text" ng-repeat="i in getItterator(option.count)" ng-model="SOME_VALUE_TO_BE_USED_BELOW"/>
Output the value based on what's entered above in the textboxes (SOME_VALUE_TO_BE_USED_BELOW)
</li>
</ul>
</label>
</li>
</ul>
</div>
</div>
and my js:
function MyCtrl($scope) {
$scope.availableOptions = [{"id":"1","name":"easy","count":"2"},{"id":"2","name":"medium","count":"3"},{"id":"3","name":"hard","count":"2"}];
$scope.getItterator=function(n){
var a = new Array();
for(var i=1; i <= n; i++)
a.push(i);
return a;
};
}
Try ng-model="option.checked":
<input type="checkbox" name="opt_{{option.id}}" id="opt_{{option.}}" ng-model="option.checked"/>
And then you can access this property further below like this:
<ul ng-show="option.checked">
DEMO
If you need to also reference the text box inputs. You create a new property (values) on the option. Like this:
{"id":"1","name":"easy","count":"2",values:[]}
Html:
<div ng-repeat="i in getItterator(option.count)">
<input type="text" ng-model="option.values[$index]"/>
{{option.values[$index]}}
</div>
DEMO
Use this:
<input type="checkbox" name="opt_{{option.id}}" id="opt_{{option.}}" ng-model="option.clicked"/>
{{option.name}}
<ul ng-show="option.clicked">
Basically, you are saying that the top checkbox should store its value in a model for each option option.clicked. And then only showing the information based on the scope item.
Updated Fiddle:
http://jsfiddle.net/CkHhJ/26/
UPDATE:
Here is another updated fiddle to answer your questions second part: http://jsfiddle.net/CkHhJ/27/
The difficulties you were having is likely because you are trying to build dynamic input models. Just bear in mind that you need to use an object for the dynamic values (not a plain string, eg: option.answers[$index].value and not just option.answers[$index]. See: AngularJS: Updating an input with a dynamic ng-model blurs on each key press

Resources