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?

rnrneverdies
  • 15,243
  • 9
  • 65
  • 95
  • I think you are on the right track. If you want to share data or behavior you should use service or factory. – nacholibre Sep 02 '14 at 17:46

1 Answers1

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
});
Fourth
  • 9,163
  • 1
  • 23
  • 28