在哪里把模型数据和行为? [英] Where to put model data and behaviour?

查看:197
本文介绍了在哪里把模型数据和行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与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.

当然,模型数据和行为可以用普通的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
}

这篇关于在哪里把模型数据和行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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