我在攀登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: ... }; });和做一个模型值是你的对象重新presentation:
And make a model value to be your object representation:
module.value('User', function(){ //user business logic });更多推荐
控制器之间共享模型
发布评论