Angular: Empty Fiddle
http://angularjs.org/
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="filterCtrl" ng-init="maxAge=30">People younger than
<input ng-model="maxAge" type="number" />years:</div>
<hr/>
<div ng-controller="infoCtrl">
<div ng-repeat="person in people" ng-show="person.visible">{{person.name}}, age {{person.age}}</div>
</div>
CSS
input {
width: 40px;
}
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller("infoCtrl", function ($scope, $timeout, person) {
person.get().then(function (response) {
// timeout to prevent '$digest already in progress' error
$timeout(function () {
$scope.people = response;
$scope.$apply();
})
});
});
myApp.controller("filterCtrl", function ($scope, person) {
$scope.$watch("maxAge", function (newValue) {
if (newValue) {
person.filterPeople(newValue);
}
});
});
myApp.service("person", function ($q, $timeout) {
var _me = this;
var AjaxGetPeople = function () {
return $timeout(function () {
var somedata = [{name: 'Marcel Sapin',age: 26},
{name: 'Anhel De Niro',age: 42},
{name: 'Johny Resset',age: 30}];
_me.people = somedata;
return somedata;
});
};
var filterPeople = function (maxAge, collection) {
if (!collection) collection = _me.people;
if (!collection) return;
angular.forEach(collection, function (p) {
p.visible = (p.age <= maxAge);
});
};
var get = function () {
if (_me.people) { // return from 'cache'
return $q.resolve(_me.people);
}
// if not 'cached', call 'ajax'
return AjaxGetPeople().then(function (response) {
// add visible property to people
filterPeople(100, response);
_me.people = response;
return response;
});
};
return {
'get': get,
'filterPeople': filterPeople
};
});