在控制器之间共享模型 [英] Share model between controllers
问题描述
我正在 angular.js 中攀登我的学习曲线,并尝试了解将所有内容放在哪里.
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;
}]);
'角度思考':像这样分享模型是个好习惯吗?
'thinking in angular': It is good practice to share the model like this?
推荐答案
我强烈建议将服务配方用于类似的事情.此外,不要简单地制作将模型公开为服务的服务.即不要这样做:
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
});
这篇关于在控制器之间共享模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!