Angular 01 - DataBinding (Arrays) examples
by Sky Sigal
HTML
<div data-ng-app="App1">
<div data-ng-controller="SomeParentCtrl">
<div data-ng-controller="SomeCtrl">
<b>Array Binding:</b><br/>
<span>Notice how ng-repeat is on repeating element (the li), NOT the ul wrapper:</span>
<ul><li data-ng-repeat='x in someArray' data-ng-bind='x'/></ul>
<span>Can also bind to properties within the repeating value:</span>
<ol><li data-ng-repeat='x in someObjectArray' data-ng-bind='x.name'/></ol>
<span>Arrays can be filtered as well:<span>
<ol><li data-ng-repeat="x in someObjectArray |filter:type='m'" data-ng-bind='x.name'/></ol>
<span>Arrays can be filtered, and ordered (desc in this case):<span>
<!-- notice how atypical syntax: use +/- to order by ascending/descending -->
<ol><li data-ng-repeat="x in someObjectArray |filter:type='m'|orderBy:'x.-name'" data-ng-bind='x.name'/></ol>
<span>Arrays can be custom filtered using a scoped filter:</span>
<ol><li data-ng-repeat="x in someObjectArray |filter:containsW" data-ng-bind='x.name'/></ol>
<span>Arrays can be pushed through a pipe handler:</span>
<ol><li data-ng-repeat="x in someObjectArray |containsST" data-ng-bind='x.name'/></ol>
</div>
</div>
</div>
JavaScript
var app1 = angular.module('App1', []);
//note how '$scope' is mapped to $s:
app1.controller('SomeParentCtrl', ['$scope', function ($s) {}]);
app1.controller('SomeCtrl', ['$scope', function ($scope) {
//an array of scalars:
$scope.someArray = ['animals','bananas','cars'];
//an array of objects:
$scope.someObjectArray = [{name:'ants',type:'i'},{name:'bats',type:'m'},{name:'cows',type:'m'}];
//defining a custom pipe filter for this scope only:
//notice how we have to '.' into the current object to check the name:
$scope.containsW = function(x){return x.name.indexOf('w')>-1;}
}]);
//If you need a global filter:
app1.filter('containsTS', function () {
return function(items){
var c = 'st';
var filtered = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.name.indexOf(c)>-1) {
filtered.push(item);
}
}
return filtered;
};
});