Share model between controllers

你。 提交于 2019-12-22 12:21:15

问题


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 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
});


来源:https://stackoverflow.com/questions/25629263/share-model-between-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!