Skip to content

Instantly share code, notes, and snippets.

@elisechant
Created March 8, 2015 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elisechant/df86b13d87a7d8d1ba13 to your computer and use it in GitHub Desktop.
Save elisechant/df86b13d87a7d8d1ba13 to your computer and use it in GitHub Desktop.
Angular collection and item controllers
<!DOCTYPE html>
<html ng-app="app">
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/angular-route/angular-route.js"></script>
<script src="../bower_components/lodash/lodash.js"></script>
<script>
angular.module('app', ['ngRoute']);
angular.module('app').config(function($routeProvider) {
$routeProvider
.when('/users', {
templateUrl: '/views/users.html',
controller: 'UsersController',
controllerAs: 'usersCtrl'
})
.when('/user/:id', {
templateUrl: '/views/user.html',
controller: 'UserController',
controllerAs: 'userCtrl'
})
.otherwise({
redirectTo: '/users'
})
});
angular.module('app').service('UserService', function($q) {
var users = [
{id:1,name:'Mickey'},
{id:2,name:'Sam'},
{id:3,name:'Penny'}
];
return {
getAll: function() {
return $q.when(users);
},
getOne: function(id) {
return $q.when(_.findWhere(users, {id:Number(id)}));
}
}
});
angular.module('app').controller('UsersController', function(UserService) {
var self = this;
self.model = [];
UserService.getAll().then(function(users) {
self.model = users;
});
});
angular.module('app').controller('UserController', function(UserService, $scope, $routeParams) {
var self = this;
self.model = {};
if ($scope.$parent && !_.isEmpty($scope.$parent.user)) {
self.model = $scope.$parent.user;
} else {
UserService.getOne($routeParams.id).then(function(user) {
self.model = user;
});
}
self.saveUser = function(id) {
debugger;
}
});
</script>
</head>
<body>
<a href="#/users">Users</a>
<a href="#/user/1">User 1</a>
<a href="#/user/2">User 2</a>
<a href="#/user/3">User 3</a>
<script type="text/ng-template" id="/views/users.html">
<pre>UsersController</pre>
<div ng-repeat="user in usersCtrl.model" ng-controller="UserController as userCtrl">
<div ng-include="'/views/user.html'"></div>
</div>
</script>
<script type="text/ng-template" id="/views/user.html">
<pre>UserController</pre>
<input type="text" ng-model="userCtrl.model.name" />
<button ng-click="userCtrl.saveUser(userCtrl.model.id)">Save</button>
</script>
<div ng-view></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment