在哪里放置模型数据和行为?[tl;博士;使用服务] [英] Where to put model data and behaviour? [tl; dr; Use Services]

查看:18
本文介绍了在哪里放置模型数据和行为?[tl;博士;使用服务]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的最新项目使用 AngularJS.在文档和教程中,所有模型数据都放入控制器范围内.我知道必须在那里供控制器使用,从而在相应的视图中使用.

I am working with AngularJS for my latest project. In the documentation and tutorials all model data is put into the controller scope. I understand that is has to be there to be available for the controller and thus within the corresponding views.

然而,我认为该模型实际上不应该在那里实现.例如,它可能很复杂并且具有私有属性.此外,人们可能希望在另一个上下文/应用程序中重用它.将所有东西都放入控制器中完全打破了 MVC 模式.

However I dont think the model should actually be implemented there. It might be complex and have private attributes for example. Furthermore one might want to reuse it in another context/app. Putting everything into the controller totally breaks MVC pattern.

这同样适用于任何模型的行为.如果我要使用 DCI 架构 并将行为与数据模型分开,我将不得不引入额外的对象来保持行为.这将通过引入角色和上下文来实现.

The same holds true for the behaviour of any model. If I would use DCI architecture and separate behaviour from the data model, I would have to introduce additional objects to hold the behaviour. This would be done by introducing roles and contexts.

DCI == Data C协作I交互

DCI == Data Collaboration Interaction

当然,模型数据和行为可以用普通的 javascript 对象或任何类"模式来实现.但是 AngularJS 的方法是什么?使用服务?

Of course model data and behaviour could be implemented with plain javascript objects or any "class" pattern. But what would be the AngularJS way to do it? Using services?

所以归结为这个问题:

如何按照 AngularJS 最佳实践实现与控制器分离的模型?

How do you implement models decoupled from the controller, following AngularJS best practices?

推荐答案

如果您希望某些东西可供多个控制器使用,您应该使用服务.这是一个简单的人为示例:

You should use services if you want something usable by multiple controllers. Here's a simple contrived example:

myApp.factory('ListService', function() {
  var ListService = {};
  var list = [];
  ListService.getItem = function(index) { return list[index]; }
  ListService.addItem = function(item) { list.push(item); }
  ListService.removeItem = function(item) { list.splice(list.indexOf(item), 1) }
  ListService.size = function() { return list.length; }

  return ListService;
});

function Ctrl1($scope, ListService) {
  //Can add/remove/get items from shared list
}

function Ctrl2($scope, ListService) {
  //Can add/remove/get items from shared list
}

这篇关于在哪里放置模型数据和行为?[tl;博士;使用服务]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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