Last active
August 29, 2015 14:02
-
-
Save mrded/e19001959e6297cdc97a to your computer and use it in GitHub Desktop.
AngularJS: Version with global variables.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}); | |
}; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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