How to pass list to angular array - angularjs

I am a new to angular... I have an object list that I would like to pass to angular and use the ng-repeat function.
Using NameList that was passed from my controller, I would like to display a list of id-names-states. Before, I did the following...
<ul>
#foreach (var item in Model.NameList) {
<li>item.id - item.names - item.states</li> }
</ul>
the list would be something like...
id: '1', name: 'John Doe', city: 'Phoenix'
id: '2', name: 'Tony Hope', city: 'Queens'
id: '3', name: 'Jane Doe', city: 'Frederick'
id: '4', name: 'John Smith', city: 'Miami'
id: '5', name: 'Tom Ford', city: 'Atlanta'
After realizing angulars capabilities I would like to set up the list, with the ability to have the user filter based on names
So my question is, How do I pass the NameList object to get populated with angular, or can I just populate the object and tie the list to angular somehow?
This is what I have so far
<div id="angularWrapper" data-ng-app="" data-ng-controller ="SimpleController">
<div>Name:
<input type="text" data-ng-model="name" />
</div>
#*I would like to pass Model.NameList to customers*#
<div data-ng-model="#Model.NameList"></div>
<br />
<ul>
<li data-ng-repeat="cust in customers | filter:name">{{cust.id + - + cust.name + - + cust.state}}</li>
</ul>
</div>

In your controller:
$scope.customers = [
{ id: '1', name: 'John Doe', city: 'Phoenix' },
{ id: '2', name: 'Tony Hope', city: 'Queens' },
{ id: '3', name: 'Jane Doe', city: 'Frederick' },
{ id: '4', name: 'John Smith', city: 'Miami' },
{ id: '5', name: 'Tom Ford', city: 'Atlanta' }
];

I think you're confused about how AngularJS binding works, you should read the guide on Data Binding: http://docs.angularjs.org/guide/databinding
In the meantime here's a simple JSFiddle I think does what you're looking for: http://jsfiddle.net/mikeeconroy/75WPW/1/
<div ng-controller="myCtrl">
Name: <input type="text" ng-model="name" />
<ul>
<li ng-repeat="cust in customers | filter:name">{{cust.id}} - {{cust.name}} - {{cust.city}}</li>
</ul>
</div>
And the controller:
angular.module('myApp',[])
.controller('myCtrl', ['$scope','mySrv',function ($scope,mySrv) {
$scope.name = '';
$scope.customers = [];
$scope.customers = mySrv.getCustomers();
}])
// fake service, substitute with your server call ($http)
.factory('mySrv',function(){
var customers = [
{id: '1', name: 'John Doe', city: 'Phoenix'},
{id: '2', name: 'Tony Hope', city: 'Queens'},
{id: '3', name: 'Jane Doe', city: 'Frederick'},
{id: '4', name: 'John Smith', city: 'Miami'},
{id: '5', name: 'Tom Ford', city: 'Atlanta'}
];
return {
getCustomers : function(){
return customers;
}
};
});
You could also set $scope.customers by using the resolve function of your route.

I came up with a solution that may have a possible alternative...
<div id="angularWrapper" data-ng-app="demoApp" data-ng-controller="SimpleController">
<div>
Name:
<input type="text" data-ng-model="name" />
</div>
<div>
<ul>
<li data-ng-repeat="eg in List | filter: name">{{ eg.Name }}</li>
</ul>
</div>
<br />
<script>
$(function () {
var scope = angular.element('#angularWrapper').scope();
#foreach (var npo in Model.NameList)
{
#: scope.AddList({ Name: '#eg.Name' });
}
scope.$apply();
});
</script>
</div>
.js file
function getList() {
var self = this;
self.Name = "";
}
var demoApp = angular.module('demoApp', []);
demoApp.controller('SimpleController', SimpleController); //could just load the function($scope) from simplecontroller..
function SimpleController($scope) {
$scope.List = [];
$scope.AddList = function (data) {
var eg = new getList();
eg.Name = data.Name;
$scope.List.push(eg);
}
}

Related

AngularJS: How to bind properties of an object to scope

I am new to use AngularJS and I am an absolute beginner. I tried using filters. I tried binding to the properties instead of directly binding the object. But the code shows {{x.people}} as the output instead of showing the list. What am I missing out here?
<!DOCTYPE html>
<html>
<head>
<title>ANGULAR APP</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
</head>
<body ng-app="myApp" ng-controller="myFirstController">
<p>Type a letter in the input field:</p>
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in model.people">
{{ x.name }}
</li>
</ul>
</body>
<script>
var app = angular.module('myApp', []);
var myFirstController = function($scope) {
$scope.model = {
people: [{
name: 'Jani',
country: 'Norway'
},
{
name: 'Carl',
country: 'Sweden'
},
{
name: 'Margareth',
country: 'England'
},
{
name: 'Hege',
country: 'Norway'
},
{
name: 'Joe',
country: 'Denmark'
},
{
name: 'Gustav',
country: 'Sweden'
},
{
name: 'Birgit',
country: 'Denmark'
},
{
name: 'Mary',
country: 'England'
},
{
name: 'Kai',
country: 'Norway'
}
];
};
}
app.controller('myFirstController', myFirstController);
</script>
</html>
there is an unnecessary ; at the end of your json data:
$scope.model = {
people:[
... // your data
{name:'Kai',country:'Norway'}]; // <------ here the ; is illegal
};
}
refer below fixed example:
var app = angular.module('myApp', []);
var myFirstController = function($scope) {
$scope.model = {
people: [{
name: 'Jani',
country: 'Norway'
},
{
name: 'Carl',
country: 'Sweden'
},
{
name: 'Margareth',
country: 'England'
},
{
name: 'Hege',
country: 'Norway'
},
{
name: 'Joe',
country: 'Denmark'
},
{
name: 'Gustav',
country: 'Sweden'
},
{
name: 'Birgit',
country: 'Denmark'
},
{
name: 'Mary',
country: 'England'
},
{
name: 'Kai',
country: 'Norway'
}
]
};
}
app.controller('myFirstController', myFirstController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myFirstController">
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in model.people | filter: {name: test}">
{{ x.name }}
</li>
</ul>
</div>

Angular - How to filter data being displayed using ng-repeat based on select/options pick by user?

Data should be displayed based on the options field (by ng-repeating) (please see below). For example, if user picks 'The Best Company Denim', only users belonging to that company should be displayed. I tried out filter but that doesn't seem to work, I have tried to write a function that checks for the chosen option which works but then I don't know how to display that (tried to loop through the users array and add to a new array, then ng-repeat through that array). anyone can help? Thanks!!!!
<div ng-app="app" ng-controller="appCtrl">
<select ng-model="selectedAccount" ng-options="account.name for account in companies" ng-change="change()">
</select>
<div ng-repeat="company in companies">
<div ng-repeat="user in company.users">
<p>{{user.firstName}} | filter: 'selectedAccount'</p>
</div>
<div>
</div>
app.controller('appCtrl', function($scope){
$scope.companies = [{
name: 'The Best Company Denim',
users: [{
firstName: 'Alex',
lastName: 'D',
number: 1234
}, {
firstName: 'Sarah',
lastName: 't',
number: 14
}, {
firstName: 'J',
lastName: 'd',
number: 07
}]
}, {
name: 'The Best Company Elegant',
users: [{
firstName: 'Alx',
lastName: 'B',
number: 1234
}, {
firstName: 'Seth',
lastName: 'w',
number: 12
}, {
firstName: 'J.S',
lastName: 'B',
number: 7
}]
}, {
name: 'The Best Company by Julia',
users: [{
firstName: 'Aleddddx',
lastName: 'l',
number: 1234
}, {
firstName: 'Maggy',
lastName: 'n',
number: 1
}, {
firstName: 'Ja',
lastName: 'Key',
number: 123
}]
}]
$scope.change = function() {
var x = "";
for (var i = 0; i < $scope.selectedAccount.users.length; i++) {
console.log($scope.selectedAccount.users[i])
x += $scope.selectedAccount.users[i]
}
return x;
}
});
At first, you're using filter in a incorrect way.
Filter is used for arrays. So you must use like this:
<div ng-repeat="element in array | filter: param">
In your specific case, you want to filter the elements in array by the name property. So you should write the following:
<div ng-repeat="company in companies | filter: { name: selectedAccount }">
Also, in your ng-options, in order to bind the name of company to the selectedAccount variable use the as syntax:
<select ng-model="selectedAccount" ng-options="account.name as account.name for account in companies">
</select>
Please refer to the following snippet:
(function() {
"use strict";
angular
.module('app', [])
.controller('appCtrl', function($scope) {
$scope.companies = [{
name: 'The Best Company Denim',
users: [{
firstName: 'Alex',
lastName: 'D',
number: 1234
}, {
firstName: 'Sarah',
lastName: 't',
number: 14
}, {
firstName: 'J',
lastName: 'd',
number: 7
}]
}, {
name: 'The Best Company Elegant',
users: [{
firstName: 'Alx',
lastName: 'B',
number: 1234
}, {
firstName: 'Seth',
lastName: 'w',
number: 12
}, {
firstName: 'J.S',
lastName: 'B',
number: 7
}]
}, {
name: 'The Best Company by Julia',
users: [{
firstName: 'Aleddddx',
lastName: 'l',
number: 1234
}, {
firstName: 'Maggy',
lastName: 'n',
number: 1
}, {
firstName: 'Ja',
lastName: 'Key',
number: 123
}]
}];
});
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
</head>
<body ng-controller="appCtrl">
<div>
<select ng-model="selectedAccount" ng-options="account.name as account.name for account in companies">
</select>
<hr>
<div>
Selected company: {{selectedAccount}}
</div>
<hr>
<div ng-repeat="company in companies | filter: { name: selectedAccount }">
<div ng-repeat="user in company.users">
<p>{{user.firstName}}</p>
</div>
<div>
</div>
</div>
</div>
</body>
</html>
Note that you even don't need to call the (ng-change) anymore.

Filter with more than one checkbox

I found a guide how to filter with one checkbox. But i wonder how can i filter on two checkboxes at the same time? I wanna add filter on Size. Sorry if im unclear.
(function () {'use strict';
angular.
module('myApp', []).
controller('WineCtrl', WineCtrl);
// Functions - Definitions
function WineCtrl() {
// Variables - Private
var self = this;
// Variables - Public
self.filter = {};
self.wines = [
{name: 'Wine A', category: 'red', size: '1'},
{name: 'Wine B', category: 'red', size: '1'},
{name: 'Wine C', category: 'white', size: '2'},
{name: 'Wine D', category: 'red', size: '2'},
{name: 'Wine E', category: 'red', size: '3'},
{name: 'Wine F', category: 'white', size: '3'},
{name: 'Wine G', category: 'champagne', size: '4'},
{name: 'Wine H', category: 'champagne', size: '4'}
];
// Functions - Public
self.filterByCategory = filterByCategory;
self.filterBySize = filterBySize;
self.getCategories = getCategories;
// Functions - Definitions
function filterByCategory(wine) {
return self.filter[wine.category] || noFilter(self.filter);
}
function filterByCategory(size) {
return self.filter[size.category] || noFilter(self.filter);
}
function getCategories() {
return (self.wines || []).
map(function (wine) { return wine.category; }).
filter(function (cat, idx, arr) { return arr.indexOf(cat) === idx; });
}
function noFilter(filterObj) {
return Object.
keys(filterObj).
every(function (key) { return !filterObj[key]; });
}
}
}());
The html is already done. The box is there.
<div ng-controller="WineCtrl as ctrl">
<h3>Categories</h3>
<div ng-repeat="category in ctrl.getCategories()">
<label>
<input type="checkbox" ng-model="ctrl.filter[category]" />
{{ category }}
</label>
</div>
<div ng-repeat="size in ctrl.getCategories()">
<label>
<input type="checkbox" ng-model="ctrl.filter[size]" />
{{ size }}
</label>
</div>
<hr />
<h3>Available Wines</h3>
<div ng-repeat="wine in (ctrl.wines | filter:ctrl.filterByCategory) as filteredWines">
{{ wine.name }} <i>({{ wine.category }})</i>
</div>
</div>

Ng-Options for objects in an array

Here I have a select, where I want to repeat the contacts on the supplier.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="AppCtrl">
Hello {{name}}
<div ng-repeat="supplier in suppliers">
{{supplier.name}}
<select ng-options="contact.id as contact.name for contact in supplier.contacts">
</select>
</div>
</div>
<script>
var app = angular.module('app',[]);
//app.directive('appDirective', function() {});
//app.factory('appService', function() {});
app.controller('AppCtrl', ['$scope', function($scope){
$scope.name = "dave";
$scope.suppliers = [
{id: 0, name: "dave", contacts : [
{id: 0, name: 'c1'},
{id: 1, name: 'c2'},
{id: 2, name: 'c3'},
{id: 3, name: 'c4'},
]},
{id: 1, name: "Steve", contacts : [
{id: 0, name: 'c1'},
{id: 1, name: 'c2'},
{id: 2, name: 'c3'},
{id: 3, name: 'c4'},
]}
]
}]);
</script>
Here I have the controller.
How come this doesn't seem to work?
http://jsfiddle.net/gnosticdave/091vpadb/1/
contacts is part of each supplier - so your array is actually supplier.contacts
select ng-options="contact.id as contact.name for contact in supplier.contacts"
^^^^^^^^^^^^^^^^^^^^
Also, ngOptions needs an ngModel
Demo: http://jsfiddle.net/091vpadb/3/
Change:
<select ng-options="contact.id as contact.name for contact in contacts">
to:
<select ng-options="contact.id as contact.name for contact in supplier.contacts">

How do you show ng-repeated children of filtered array?

I have a drop-down filtered array, but the array I'd like to use is a little more complex, with nested data, similar to this http://jsfiddle.net/vojtajina/u75us/
I'd like to combine both ideas, but can't figure out why my fiddle doesn't display the 'child nodes'
<div class="col-md-12" ng-controller="App04Ctrl">
<p>Search:
Filter:
<select ng-model="filterItem.store" ng-options="item.name for item in filterOptions.stores">
</select>
Sort:
<select ng-model="sortItem.store" ng-options="item.name for item in sortOptions.stores">
</select>
</p>
<ul>
<li ng-repeat="item in locations | orderBy:'price':reverse | filter:customFilter" >Name: {{item.name}} Price: {{item.price}} Location: {{item.location}}</li>
<ul>
<li ng-repeat="package in location.packages">{{package.name}} has services:
<ul>
<li ng-repeat="service in package.services">{{service.name}}</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
angular.js:
var app = angular.module('app04', []);
function App04Ctrl($scope) {
//Contains the filter options
$scope.filterOptions = {
stores: [
{id : 2, name : 'Show All', location: 'All Locations' },
{id : 3, name : 'Ashburn', location: 'Ashburn' },
{id : 4, name : 'San Francisco', location: 'San Francisco' },
{id : 5, name : 'Denver', location: 'Denver' },
{id : 6, name : 'Chicago', location: 'Chicago' },
{id : 7, name : 'Irvine', location: 'Irvine' }
]
};
//Contains the sorting options
$scope.sortOptions = {
stores: [
{id : 1, name : 'Price Highest to Lowest' },
{id : 2, name : 'Price Lowest to Highest' },
]
};
//Mapped to the model to filter
$scope.filterItem = {
store: $scope.filterOptions.stores[0]
}
//Mapped to the model to sort
$scope.sortItem = {
store: $scope.sortOptions.stores[0]
};
//Watch the sorting model - when it changes, change the
//ordering of the sort (descending / ascending)
$scope.$watch('sortItem', function () {
console.log($scope.sortItem);
if ($scope.sortItem.store.id === 1) {
$scope.reverse = true;
} else {
$scope.reverse = false;
}
}, true);
//Custom filter - filter based on the location selected
$scope.customFilter = function (locations) {
if (locations.location === $scope.filterItem.store.location) {
return true;
} else if ($scope.filterItem.store.location === 'All Locations') {
return true;
} else {
return false;
}
};
// Location data
$scope.locations = [{
name: "product1",
price: 198,
location: 'Ashburn',
packages: [{
name: 'Doom Patrol',
services: [{
name: 'Mento'}, {
name: 'Vox'}, {
name: 'Robotman'}]}, {
name: 'Suicide Squad',
services: [{
name: 'King Shark'}]}, {
name: 'Shadowpact',
services: [{
name: 'Zauriel'}, {
name: 'Enchantress'}, {
name: 'Ragman'}, {
name: 'Nightshade'}]}]}, {
name: "product2",
price: 402,
location: 'Chicago',
packages: [{
name: 'Metal Men'}, {
name: 'Legion of Superheroes',
services: [{
name: 'Ultra Boy'}, {
name: 'Kid Quantum'}]}]}, {
name: "product2",
price: 300,
location: 'Denver',
packages: [{
name: 'Freedom Fighters',
services: [{
name: 'Damage'}, {
name: 'Iron Munro'}]}, {
name: 'Birds of Prey',
services: [{
name: 'Huntress'}, {
name: 'Black Alice'}]}]}, {
name: "product2",
price: 1243,
location: 'Irvine',
packages: [{
name: 'The Outsiders'}, {
name: 'Zoo Crew',
services: [{
name: 'Rubberduck'}, {
name: 'Captain Carrot'}]}, {
name: 'The Elite',
services: [{
name: 'Vera Black'}, {
name: 'Manchester Black'}]}, {
name: 'Justice Legion Alpha'}]}
];
}
http://jsfiddle.net/jdacio/Vfx3y/2/
What am I missing? Am I on the right track? is there a better way to do this?
There are two problems that I see in your code above:
[1] Notice that you have closed the <li> tag, thus stopping the nesting of your ng-repeat directive to show the packages and and services of each item location. Simply remove the </li> closing tag and that should solve your first problem.
<li ng-repeat="item in locations | orderBy:'price':reverse | filter:customFilter" >
Name: {{item.name}}
Price: {{item.price}}
Location: {{item.location}}
</li> <!-- THIS IS THE PROBLEM!! -->
[2] As what Mosho mentioned, your nested ng-repeat directive is using a location reference which does not exist in the current context of its parent ng-repeat directive. The simplest solution would be to change
<li ng-repeat="package in location.packages">
to
<li ng-repeat="package in item.packages">
The resulting HTML code should be:
<ul>
<li ng-repeat="item in locations | orderBy:'price':reverse | filter:customFilter" >
Name: {{item.name}}
Price: {{item.price}}
Location: {{item.location}}
<ul>
<li ng-repeat="package in location.packages">{{package.name}} has services:
<ul>
<li ng-repeat="service in package.services">{{service.name}}</li>
</ul>
</li>
</ul>
</li>
</ul>
Instead of location.packages, it should be item.packages. (or 'location in locations' rather than 'item in locations').
<li ng-repeat="item in locations | orderBy:'price':reverse | filter:customFilter">
...
<li ng-repeat="package in location.packages">
You refer to location, but you declare item in locations.

Resources