Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

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

I am working with AngularJS for my latest project.(我正在为最新项目使用AngularJS。)

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.(我知道控制器必须可用,因此必须在相应的视图内可用。) 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.(将所有内容放入控制器中完全破坏了MVC模式。) 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.(如果我要使用DCI体系结构并将行为与数据模型分开,则必须引入其他对象来保存行为。) This would be done by introducing roles and contexts.(这可以通过介绍角色和上下文来完成。) DCI == D ata C ollaboration I nteraction(DCI == d ATA?ollaboration nteraction) Of course model data and behaviour could be implemented with plain javascript objects or any "class" pattern.(当然,可以使用简单的javascript对象或任何“类”模式来实现模型数据和行为。) But what would be the AngularJS way to do it?(但是,AngularJS的实现方式是什么?) Using services?(使用服务?) So it comes down to this question:(所以归结为这个问题:) How do you implement models decoupled from the controller, following AngularJS best practices?(遵循AngularJS最佳实践,如何实现与控制器分离的模型?)   ask by Nils Blum-Oeste translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...