Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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 has to be there to be available for the controller and thus within the corresponding views.

However, I don't 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 the MVC pattern.

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 Collaboration Interaction

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?

So it comes down to this question:

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

1 Answer

0 votes
by (106k points)

You can use services if you want something usable by multiple controllers. Below is an example regarding the same:

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

}

Related questions

Browse Categories

...