Skip to content

Instantly share code, notes, and snippets.

@mrded
Last active August 29, 2015 14:01
Show Gist options
  • Save mrded/d9acd9e2faf35bdbb095 to your computer and use it in GitHub Desktop.
Save mrded/d9acd9e2faf35bdbb095 to your computer and use it in GitHub Desktop.
AngularJS: Example of filtering problem.
.controller('GlobalCtrl', function($rootScope, $scope, UserService, TodoService) {
$rootScope.users = [];
$rootScope.todos = [];
// Init.
UserService.all().then(function(users) {
angular.forEach(users, function(user) {
rootScope.users.push(user);
TodoService.all(user.id).then(function(todos) {
angular.forEach(todos, function(todo) {
$rootScope.todos.push(todo);
});
$rootScope.$broadcast('UPDATE_DATA', '')
});
});
});
});
<div ng-controller="GlobalCtrl">
<div ng-repeat="user in users" ng-controller="UserCtrl">
<ul>
<!-- todos must be variable -->
<li ng-repeat="todo in todos">{{todo.title}}</li>
</ul>
</div>
</div>
.service('TodoService', function($http, $q) {
this.all = function(userId) {
var deferred = $q.defer();
$http.get('/api/users/' + userId + '/todos').success(function(todos) {
return deferred.resolve(todos);
});
return deferred.promise;
};
});
.controller('UserCtrl', function($rootScope, $scope, $filter) {
$rootScope.$on('UPDATE_DATA', function(event, data) {
$scope.todos = $filter('filter')($rootScope.todos, {user_id: $scope.user.id});
});
});
.service('UserService', function($http, $q) {
this.all = function() {
var deferred = $q.defer();
$http.get('/api/users').success(function(users) {
return deferred.resolve(users);
});
return deferred.promise;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment