控制器之间共享模型 [英] Share model between controllers

查看:88
本文介绍了控制器之间共享模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在攀登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
});

这篇关于控制器之间共享模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆