Skip to content

Instantly share code, notes, and snippets.

@jacobsimeon
Last active September 17, 2015 02:35
Show Gist options
  • Save jacobsimeon/1ca2831d8fda5955e5ca to your computer and use it in GitHub Desktop.
Save jacobsimeon/1ca2831d8fda5955e5ca to your computer and use it in GitHub Desktop.
Using a 'model' in angular
// this is the constructor function of the javascript object (i.e. the `initialize` method)
var User = function(data, http) {
// copy data (presumably a simple JSON object received by a call to some API)
angular.copy(data, this);
this.http = http;
}
// add methods to the User "class"
User.prototype.fullName = function() {
return this.firstName + ' ' + this.lastName;
}
// use things that are dependency injected, like $http
User.prototype.addRole = function(roleName) {
return this.http.post('/users/' + this.id + '/roles', roleName);
}
User.prototype.save = function(){
return this.http.post(
'/users', {
email: this.email,
password: this.password
});
}
// wrap the user model in a service that can create new instances of User
// this will return a simple object that responds to `#new` and will return a new User object
// you can use dependency injection as normal here
angular.module('myApp').service('userService', function($http){
return {
new: function(data) {
// $http was injected into the service, so we can easily hand it to the model
return new User(data, $http)
},
}
});
<!-- example of using the user model in a view -->
<!-- arguably this sort of thing can be done in a filter -->
<p>
Welcome, {{ user.fullName() }
</p>
// an example of using the service in a controller
angular.module('myApp').controller('newUserController', function(userService, $scope){
// presumably $scope.user.email is bound in some view somewhere
$scope.user = userService.new({});
$scope.save = function() {
$scope.user.save().then(function(){
handleSuccess();
}, function() {
handleError();
})
};
$scope.addRole = function(roleName) {
$scope.user.addRole(roleName).then(function(){
successfullyAddedRole();
}, function() {
failedToAddRole();
})
}
});
@jacobsimeon
Copy link
Author

I've had some success with this pattern when I want my angular objects to be a little more modely. The advantage here is that the controller is less noisy and serves the single purpose of passing data between model and view.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment