问题
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