我正在爬上 angular.js 的学习曲线,并尝试了解将所有内容放在哪里。
在这种情况下,我想知道使用服务在 Controller 之间共享模型是否是最佳实践。
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;
}]);
“以 Angular 思考”:像这样共享模型是很好的做法吗?
最佳答案
我强烈建议使用服务配方来完成类似的事情。另外,不要简单地制作一个将模型公开为服务的服务。即不要这样做:
.service('UserService', function(){
return {
changePassword: ...
updateUsername: ...
addEmail: ...
};
});
相反,让服务成为与模型交互的接口(interface):
.service('UserService', function(User){
return {
getById: ...
getAll: ...
save: ...
};
});
并将模型值作为您的对象表示:
module.value('User', function(){
//user business logic
});
关于angularjs - 在 Controller 之间共享模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25629263/