在哪里放置模型数据和行为? [TL;博士;使用服务] [英] Where to put model data and behaviour? [tl; dr; Use Services]
问题描述
我正在与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
}
这篇关于在哪里放置模型数据和行为? [TL;博士;使用服务]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!