how to create object while using ng-repeat and array in angularjs - javascript

Hello Everyone I have face a problem to create a object with ng-repeat. when i declare the Object then the same value in filled in the text box which has same ng-model value. if i am not Declare the object then duplicacy is not occures.
If i am declare the $scope.user = {}; in js file then problem is occures. please check this. Give me a solution ASAP.
My Fiddle Link Please Check This http://jsfiddle.net/Ladjkp5s/1/
Here is my Html file
<div ng-app="myApp">
<div ng-controller='MainController' ng-init="start = 0; end = 5;">
Start: <input ng-model="start"> End: <input ng-model="end">
<ul>
<li ng-repeat="item in items | slice:start:end">{{item + 1}}
<div>
Name: <input type="text" ng-model="user.name"><br>
Address: <input type="text" ng-model="user.add"><br>
Phone: <input type="text" ng-model="user.phn"><br>
ZipCode: <input type="text" ng-model="user.zip">
</div>
</li>
</ul>
</div>
</div>
Here is my JS File
var app = angular.module('myApp', []);
app.filter('slice', function() {
return function(arr, start, end) {
return arr.slice(start, end);
};
});
app.controller('MainController', function($scope) {
$scope.items = [];
$scope.user ={};
for (var i = 0; i < 5; i++) $scope.items.push(i);
});
Thanks.

The problem is that you are using same ng-model for every item.(user.fieldName) you have to use item.fieldName.
<div ng-app="myApp">
<div ng-controller='MainController' ng-init="start = 0; end = 5;">
Start: <input ng-model="start"> End: <input ng-model="end">
<ul>
<li ng-repeat="item in items | slice:start:end">{{item.index + 1}}
<div>
Name: <input type="text" ng-model="item.name"><br>
Address: <input type="text" ng-model="item.add"><br>
Phone: <input type="text" ng-model="item.phn"><br>
ZipCode: <input type="text" ng-model="item.zip">
</div>
</li>
</ul>
</div>
</div>
http://jsfiddle.net/3akwk7tv/

Yuu can not loop in controller function, but u can create controller that loops in html like in this example
<ul>
<li ng-repeat="theItem in myData.items">{{theItem.text}}</li>
</ul>
<script>
angular.module("myapp", [])
.controller("MyController", function($scope) {
$scope.myData = {};
$scope.myData.items = [ {text : "one"}, {text : "two"}, {text : "three"} ];
});
</script>

Related

Angular JS collect all input values from a div

I am new to Angular JS, I created a div with input elements and I didn't use ng-model for input boxes.
<div class="row">
<br>
<div class="col-sm-10" id="rankingForm" >
<p ng-repeat=" x in $ctrl.outputProductAttributeValueList">
{{x}} <input type="text" />
</p>
<br>
<button type="submit" ng-click="$ctrl.onRankingFormSubmit()"> SUBMIT</button>
</div>
</div>
When I click on submit button I have to access all input values .Please help me how to do that .. I tried as below.
angular.module("productList")
.component("productList",{
templateUrl : "product-list/product-list.template.html",
controller : ["$http" ,"$scope","$document",function productListController($http,$scope,$document){
var self = this;
self.outputProductAttributeValueList =[ "age", "gender","all"];
self.onRankingFormSubmit = function () {
var queryResult = $document[0].getElementById("rankingForm")
console.log(queryResult);
// HERE queryResult is printing how to proceed further
};
}]
});
Now I want to collect all those input values dynamically created by ng-repeat. Please tell me how to do that ?
AngularJS ngModel is the standard approach for binding the view into the model instead of interacting directly with the DOM.
You can get all the inputs within the div id="rankingForm" you can do:
var inputs = $document[0]
.getElementById('rankingForm')
.getElementsByTagName('input');
Or by using Document.querySelectorAll():
var inputs = $document[0].querySelectorAll('#rankingForm input');
Once you have the inputs than iterate over all of them to get the values.. Notice that I have added attribute name to the inputs:
Code whitout ngModel:
angular
.module('App', [])
.controller('AppController', ['$scope', '$document', function ($scope, $document) {
$scope.outputProductAttributeValueList = ['age', 'gender', 'all'];
$scope.onRankingFormSubmit = function () {
var inputs = $document[0].querySelectorAll('#rankingForm input');
inputs.forEach(function(input) {
console.log(input.name + ': ' + input.value);
});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController" class="row">
<br>
<div class="col-sm-10" id="rankingForm" >
<p ng-repeat="x in outputProductAttributeValueList">
{{x}} <input type="text" name="{{x}}" />
</p>
<br>
<button type="submit" ng-click="onRankingFormSubmit()">SUBMIT</button>
</div>
</div>
Code with ngModel:
angular
.module('App', [])
.controller('AppController', ['$scope', '$document', function ($scope, $document) {
$scope.outputProductAttributeValueList = ['age', 'gender', 'all'];
// Model inputs
$scope.inputs = {};
$scope.onRankingFormSubmit = function () {
$scope.outputProductAttributeValueList.forEach(function(input) {
// Access to model inputs: $scope.inputs[input]
console.log(input + ': ' + $scope.inputs[input]);
});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController" class="row">
<br>
<div class="col-sm-10" id="rankingForm" >
<p ng-repeat="x in outputProductAttributeValueList">
{{x}} <input type="text" ng-model="inputs[x]" />
</p>
<br>
<button type="submit" ng-click="onRankingFormSubmit()">SUBMIT</button>
</div>
</div>

Angular js - Not able to push to an array

I'm trying to push some info to an array and show it with ng-repeat but for some reason it's not working
This is my controller:
(function () {
'use strict';
angular
.module('app.article')
.controller('Article', Article);
function Article($location) {
var vm = this;
vm.comments = [];
vm.addComment = addComment;
function addComment() {
vm.comments.push(vm.newComment);
vm.newComment = {};
}
}
})();
Here's the plunkr: https://plnkr.co/edit/jPOJDXoG1vgNfsDzyJAD?p=preview
Thanks for the help
for your controller you are using a controller As syntax so you will have to refer to scope variables with a prefix of vm.
<div ng-controller="Article as vm">
<form ng-submit="vm.addComment()">
<textarea placeholder="Sign in to share your thoughts." ng-model="vm.newComment.comment"></textarea>
<input type="text" class="form-control" ng-model="vm.newComment.user">
<input type="submit" class="btn btn-primary" value="Post">
</form>
<ul>
<li ng-repeat="comment in vm.comments">{{comment.user}} - {{comment.comment}}</li>
</ul>
</div>
Also in your controller you have to initialize a newComment object
function Article($location) {
var vm = this;
vm.comments = [];
vm.addComment = addComment;
vm.newComment = {user: '', comment: ''}
function addComment() {
vm.comments.push(vm.newComment);
vm.newComment = {};
}
}
Updated Plunker
<div ng-controller="Article as vm">
<form ng-submit="vm.addComment()">
<textarea placeholder="Sign in to share your thoughts." ng-model="vm.newComment.comment"></textarea>
<input type="text" class="form-control" ng-model="vm.newComment.user">
<input type="submit" class="btn btn-primary" value="Post">
</form>
<ul>
<li ng-repeat="comment in vm.comments">{{comment.user}} - {{comment.comment}}</li>
</ul>
</div>
Here is the updated plunkr
https://plnkr.co/edit/HK4WIYCF6poMXncBU9Uk?p=preview

how to filter the data from text box in angularjs

**Hi,i am filtering the array data from textbox but the code is not working properly can any one help me please.the data from back end
self.AdminLineDetails = function(data) {
$scope.details = [];
$scope.details = data.GoalData;
console.log(data);
}
<div class="row">
<div class="col-md-12">
<input ng-model="query" type="text" class="form-control" placeholder="Filter by name or number">
</div>
<div>
<tbody>
<tr ng-repeat="detail in details|filter:query">
<td>{{detail.firstName}}
</td>
<td>{{detail.lastName}}
</td>
<td>{{detail.mdn}}
</td>
</tr>
</tbody>
</div>
**
You can specify on which property you are trying to filter, do something like
<tr ng-repeat="detail in details|filter: {firstName: query}">
<input type="text" ng-model="search">
<ul ng-repeat="oneauth in authorisations[0]">
<li ng-repeat="entry in oneauth | nameFilter:search">{{entry.auth.name}}</li>
</ul>
JS
var app = angular.module('myapp', [], function () {});
app.controller('AppController', function ($scope) {
$scope.authorisations = [{
"authorisations":[
{
"auth":{
"number":"453",
"name":"Apple Inc."
}
},
{
"auth":{
"number":"123",
"name":"Microsoft Inc."
}
}]
}];
});
app.filter('nameFilter', function(){
return function(objects, criteria){
var filterResult = new Array();
if(!criteria)
return objects;
for(index in objects) {
if(objects[index].auth.name.indexOf(criteria) != -1) // filter by name only
filterResult.push(objects[index]);
}
console.log(filterResult);
return filterResult;
}
});
Check this sample
http://jsfiddle.net/yctchgnk/

Remove item from the list if checked

I have a list of items with a checkbox, and i have delete button. The delete only works if the item in the list is checked.
So for example i have
$scope.list = [{
name:'Groceries',
check: false
}, {
name:'Laundry',
check:false
},
{
name:'Cleaning',
check:false
}];
and in my HTML
<ul>
<li ng-repeat="values in list">
<input type="checkbox" ng-model="values.check"/>
<span>{{values.name}}</span>
</li>
</ul>
<button>Delete</button>
This is just the snippet of the code i have the controller declared and bootstrapped with ng-app
You should use Angular native directive ng-checked
<input type="checkbox" ng-checked="values.check"/>
You can use a filter for this:
HTML
<body ng-app="app" ng-controller='Ctrl'>
<ul>
<li ng-repeat="values in list">
<input type="checkbox" ng-model="values.check"/>
<span>{{values.name}}</span>
</li>
</ul>
<button ng-click="remove((list | filter:{check:true}))">Delete</button>
</body>
Controller
$scope.remove = function(items) {
alert('removing ' + items.length + ' items');
$scope.list = $filter('filter')($scope.list, { check: false});
}
Demo Plunker
<body ng-controller="MyController">
<ul>
<li ng-repeat="values in list">
<input type="checkbox" ng-model="values.check" />
<span>{{values.name}}</span>
</li>
</ul>
<button ng-click="deleteItems()">Delete</button>
</body>
controller:
myApp.controller('MyController', function($scope, $filter) {
$scope.list = [ {
name : 'Groceries',
check : false
}, {
name : 'Laundry',
check : false
}, {
name : 'Cleaning',
check : false
} ];
$scope.deleteItems = function() {
$scope.list = $filter('filter')($scope.list, {check : false})
}
})

ng-click does nothing (todo list example)

I try to play around with some test in angular. but failed to add item in a todo list app sample:
app.controller('MainControl', function($scope){
$scope.tasks = [
{
"name":"task 1",
},
{"name":"task 2",
}
];
var addTask = function(){
$scope.tasks.push({
"name": $scope.input,
});
$scope.input = "";
};
});
I wonder why it doesn't work, no error in the console.
my html
<body ng-controller="MainControl">
<div>
<label>I want to:</label>
<input type="text" ng-model="input">
<button ng-click="addTask()">Add</button>
</div>
<div>
<ul ng-repeat="task in tasks">
<li>{{task.name}}</li>
</ul>
</div>
</body>
addTask must be a $scope property, i.e. $scope.addTask = function() {} instead of var addTask = function() {}.
Edit after comments:
<form ng-submit="addTask()">
<label>I want to:</label>
<input type="text" ng-model="input">
<button type="submit">Add</button>
</form>

Categories