How to give dynamic values to ng-model - angularjs

I am appending a div into the DOM on user click. To get the user entered values I want to attach ng-model to input fields. As I don't know the total number of div's which user will append, I want to keep the values in ng-model dynamic.
Here is the code: (my-Controller)
function addDiv() {
var element = angular.element(document.createElement('my-Directive'));
var el = $compile(element)($scope);
//where to place the element
angular.element($('#add')).append(element);
$scope.insertHere = el;
//giving unique id to div element.
var objName = 'step'+number;
dataCtrl.tbt = {
"val": objName,
"tes":"arjun"
}
$(element).attr("id",objName);
console.log(objName);
number++;
};
//html where I want to put dynamic ng-model
<div class="form-group">
<div class="col-xs-4">
<label for="target">Target:</label>
</div>
<div class="col-xs-7">
<input id="target" placeholder="Target" ng-model="dataCtrl.tbt[dataCtrl.tbt.val]" type="text" class="form-control"/>
</div>

You can use ng-repeat to add input boxes dynamically
<div ng-repeat="in in input">
<label>{{$index+1}}</label><input type="text" ng-model="in.value">
</div>
<button ng-click="addInput()">Add</button>
And push an empty value to the Array on ng-click of add button
Plunker Link
Hope this Helps!!

Related

Binding in ng-repeat

I have a div which displays the text. And below it have a textarea which can edit the text of the div.On typing the text of textarea the div text changes.I don't want this to happen.The problem is both div and text area is in ng-reapeat.Otherwise I would have used different scope for both.
<div ng-repeat="item in list">
<div>
{{item.text}} // this is the text that is changing when typing in text area
</div>
<div>
<textarea rows="4" cols="50" class="form-control" ng-model="item.text" required>{{item.text}}
</textarea>
</div>
</div>
Here is the link to my issue
http://codepen.io/ankitappuria27/pen/pyVzaj
If you don't want to change the text in your div, just use a one time binding like:
{{::item.text}}
Note: Any change you make inside your textarea will ofcourse still affect your models text value. The changes just won't be visible in your div.
Example:
http://codepen.io/anon/pen/VaxGOp
Documentation:
https://docs.angularjs.org/guide/expression#one-time-binding
In your JS file you may add element in json for displaying header text just like below:
app.controller('ctrl', function($scope) {
$scope.newitem = '';
$scope.list = [
{
"order":1,
"header":"Black", // header text
"text":"Black"
},
{
"order":2,
"header":"Blue", // header text
"text":"Blue"
}
];
});
and your html for binding should be as below
<div>
{{item.header}}
</div>
<div>
<textarea rows="4" cols="50" class="form-control" ng-model="item.text" required>{{item.text}}
</textarea>
</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

DOM swapping in Angular JS

Basically I have two Divs in a page out of which only one will be visible at a time.
I have a text input placed inside my first div which is shown my default.
Now if the first div is hidden and the second DIV is shown,
I want to swap the text input DOM in to the second DIV. The ID of the textinput and the value it has needs to be retined on swapping.
I have a reference of the text input to be swapped in my custom directive (ref-comp in the below snippet).
How can i achieve this in angularJS ? Please help me here.
<div id="1">
<div id ="container1">
<input type="text" id="text1">
</input>
</div>
<div id ="container1">
<ref-comp id="ref1" refId ="text1">
</ref-comp>
</div>
</div>
Please have a look on it this might be help.
var app = angular.module('myApp', []);
app.controller('IndexCtrl', function($scope) {
$scope.showme = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="1" data-ng-app="myApp" data-ng-controller="IndexCtrl">
<div id ="container1" ng-show="showme">
value of text filed of div 1: {{divAVarialbe.text1}} <br>
<input type="text" id="text1" ng-model="divAVarialbe.text1">
</input>
</div>
<div id ="container1" ng-show="!showme">
value of text filed of div 2 : {{divBVarialbe.text1}} <br>
<input type="text" id="text1" ng-model="divBVarialbe.text1">
<ref-comp id="ref1" refId ="text1">
</ref-comp>
</div>
<button ng-click="showme = !showme" ng-show="!showme">Show div 1</button>
<button ng-click="showme = !showme" ng-show="showme">Show div 2</button>
</div>
You can use ng-show to swap the div and and scope variables to access the input filed of the DOM.
suppose that if use to scope variable lets say divAVarialbe and divBVariable.
then for div A divAVarialbe will be use i.e all the child model will be go inside divAVarialbe so your data str will be
divAVarialbe={"text1":"value of textfild","otherModel":"",...}
same for Div B.
In this way you can differentiate the DOM.
It base on how much you have knowledge of Object.
assume it like mvc pattern then it will be easy to code.
might be this will help.

Angular : pass mutliple values to the controller

Let's say i have a drop drown list that i add dynamicly in my html template:
<button type="button" ng-click="addRow()" style="margin-bottom:5px;">Add cities </button>
<div ng-repeat="city in cities">
<select ng-model="cities_$index"
ng-options="n.id as n.name for n in citiesList"
class="form-control"
ng-required="true">
<option value="">-- Choose City --</option>
</select>
</div>
Angular Controller :
$scope.addRow = function () {
var newrow = [];
if ($scope.cities.length === 0) {
newrow.push({ 'cities': $scope.cities_0 });
}
else {
$scope.cities.forEach(function (row, key) {
var city= '$scope.cities_'+key; // in php i can do this
//but i dont know how to do it with Js/Angular
console.log('row' + city);
newrow.push({ 'cities': city});
console.log(newrow);
});
}
$scope.cities.push(newrow);
}
I tried this to retrieve the values from the cities selected but i have undefined values.
$scope.send = function () {
angular.forEach($scope.cities, function (value, key) {
console.log(value.id); // the id from the ng-options
};
In a regular html code i just add name="city" and i retrieve all the cities added in my input box. But how i can retrieve thoses cities from the ng-model in my controller ?
I know i'm doing something wrong, but since i'm new with angular i'm trying !!
Thank you
supposing that the key (city) is inside your datas array, you can do :
<div ng-repeat="data in datas">
<input type="text">{{data.name}}
</div>
ng-model is still unique. What you are missing here is that ng-repeat creates a child scope for each item. Therefore, the value of ng-model is unique for EACH child scope. ng-model doesn't behave the same way as plain HTML input and having multiple inputs with the same ng-model will only point to the same object in memory. And not, "add up" values to the property city as you would expect in plain HTML inputs.
If you are using the object datas in your ng-repeat, it's kind of common practice that your <input /> would bind to a item property of datas.
<div ng-repeat="data in datas">
<input type="text">{{data.city}}
</div>

How to add object properties from ng-checked items to my ng-model object

I have four input fields which I'm using to add properties to a single object using ng-model= model.propertyName. I have a series of check boxes that I'm creating with ng-repeat that I could not figure out how to add unique propertyNames for each ng-model as they were created with the ng-repeat. As a work-around(or maybe this is correct, I'm not sure) I was able to write a function to add the checked items to an array. I was then trying to use a for-loop to iterate over the array and add each selected propertyName(string) to the ng-model object as a new property using a ng-click to call the function.
As-is when I click the "Add Technician" button I get the following error output:
TypeError: Cannot read property 'selection' of undefined
at Scope.$scope.addTechnician (..../scripts/controllers.js:
This occurs because $scope is undefined inside the conditional of my for loop in the addTechnician function. I can't understand why because when I pass $scope to the addTechnician function it recognizes the newTech inside the for loop. When I don't pass $scope to the addTechnician function it says newTech is undefined with the following error:
TypeError: Cannot set property 'cert1' of undefined
at Scope.$scope.addTechnician(.../scripts/controllers)
I'm pretty sure this has something to do with the way ng-repeat creates a new scope, which prototypically inherits from the parent scope. But again, I'm not sure.
Here is my controller
use strict';
angular.module('Carrepair2.controllers', [])
.controller('SetupCtrl', function($scope) {
$scope.certifications = [
{'name':'Engine Repair'},
{'name':'A/T & Transaxle'},
{'name':'Manual Drive Train & Axles'},
{'name':'Suspension & Steering'},
{'name':'Brakes'},
{'name':'Electrical & Electronic Systems'},
{'name':'Heating & Air Conditioning'},
{'name':'Engine Performance'},
{'name':'Light Vehicle Diesel Engines'}
];
// selected certifications
$scope.selection = [];
$scope.toggleCert = function(name) {
var idx = $scope.selection.indexOf(name);
//is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
//is newly selected
else{
$scope.selection.push(name);
}
};
$scope.addTechnician = function($scope) {
for(var i=0; i < $scope.selection.length - 1; i++){
$scope.newTech['cert' + (i + 1).toString()] = $scope.selection[i].name;
}
};
})
Here is my template
<form class="col-md-6">
<div class="input_wrapper">
<input type="text" name="first-name" ng-model="newTech.firstName" required>
<label for="first-name">First Name</label>
</div>
<div class="input_wrapper">
<input type="text" name="last-name" ng-model="newTech.lastName" required>
<label for="last-name">Last Name</label>
</div>
<div class="input_wrapper">
<input type="email" name="email" ng-model="newTech.email" required>
<label for="email">Email</label>
</div>
<div class="input_wrapper">
<input type="tel" name="phone" ng-model="newTech.phone" required>
<label for="phone">Phone</label>
</div>
<h5>Check all held ASE certifications</h5>
<ul class="list">
<li class="item item-checkbox" ng-repeat="certification in certifications">
<label class="checkbox">
<input type="checkbox" value="{{certification.name}}" ng-checked="selection.indexOf(certification.name) > -1" ng-click="toggleCert(certification)">
</label>
{{certification.name}}
</li>
</ul>
<button class="button button-block" ng-click="addTechnician()">Add Technician</button>
</form>
Ideally after the "Add Technician" button is clicked I want to end up with an object, my newTech ng-model object, that has the input field data and the properties from the checked items. Here is a jsFiddle with simplified code replicating the problem
http://jsfiddle.net/aq93z/7/
I solved it. I had to format my loop using angular.forEach(values, function(value, index){here is the jsFiddle with the solution http://jsfiddle.net/aq93z/9/. If you look at the $scope.newTech object created in the console the checkbox selections are added as properties of the newTech ng-model object.

Resources