I have two angularJS controllers that should be synchronized. The first is a filter on a list, second displays the list. I have a service user by both controllers and that makes some async ajax-like calls.
My problem is that the filter filters before the list is initialized, so when the page loads for the first time I have unfiltered results. How to solve it?
Here is my JSFiddle
Here is the code:
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
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<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>
</div>
Anhel De Niro, age 42
should not be displayed when the page is loaded initially, because my filter's max age is 30...