2

I'm climbing my learning curve in angular.js and try to understand where to put everything.

In this case I want to know if it is a best practice to use services to share the model between controllers.

var app = angular.module('module', [])

.factory('shared', ['$http', function ($http) {
  var factory = {
    "title" : "Shared Title 2"
  };
  factory.action = function () {
     // do something with this.title;
  }
  return factory;
}])

.controller('MainCtrl', ['$scope','shared', function($scope, shared) {
  $scope.shared = shared;
}])

.controller('SecondaryCtrl', ['$scope','shared', function($scope, shared) {
  $scope.shared = shared;
}]);

minimal example:

'thinking in angular': It is good practice to share the model like this?

1
  • I think you are on the right track. If you want to share data or behavior you should use service or factory. Commented Sep 2, 2014 at 17:46

1 Answer 1

2

I strongly recommend using the Service recipe for something like this. In addition, do not simply make a service that exposes the model as the service. i.e. dont do this:

.service('UserService', function(){

  return {
    changePassword: ...
    updateUsername: ...
    addEmail: ...
  };

});

Instead, let the service be an interface for interacting with the model:

.service('UserService', function(User){

 return {
  getById: ...
  getAll: ...
  save: ...
 };

});

And make a model value to be your object representation:

module.value('User', function(){
  //user business logic
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.