Skip to content

Instantly share code, notes, and snippets.

@mrded
Last active August 29, 2015 14:02
Show Gist options
  • Save mrded/e19001959e6297cdc97a to your computer and use it in GitHub Desktop.
Save mrded/e19001959e6297cdc97a to your computer and use it in GitHub Desktop.
AngularJS: Version with global variables.
app.controller('mainCtrl', function($rootScope, UserService) {
$rootScope.users = [];
$rootScope.todos = [];
// Get all users.
UserService.all().then(function(users) {
angular.forEach(users, function(user) {
$scope.users.push(user);
// Get all todos.
TodoService.all(team.id, user.id).then(function(todos) {
angular.forEach(todos, function(todo) {
$rootScope.todos.push(todo);
});
});
});
});
});
app.controller('UserCtrl', function($rootScope, $scope) {
// Easy to change $rootScope.todos, and it will affect everywhere automatically.
$scope.changeOwner = function(todoId, userId) {
angular.forEach($rootScope.todos, function(todo) {
if (todo.id == todoId) {
todo.userId = userId;
}
});
};
});
<div ng-controller="mainCtrl">
<div ng-repeat="user in users">
<ul ng-controller="UserCtrl">
<li ng-repeat="todo in todos | filter:{userId: user.id}">
{{todo.title}}
</li>
</ul>
</div>
</div>
app.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;
};
});
app.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;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment