Reputation: 1794
I am trying to move bits from a parent controller inside child controllers in an angularjs app to not pollute the main controller too much.
Here's a simplified fiddle: http://jsfiddle.net/terebentina/5RMPV/
So when I click the change button, the third letter should change to 'X'.
Initially the item_change() function was inside the main controller and was doing $scope.items[idx] = 'X'
and this worked just fine. However, since I moved it inside the ItemCtrl, I have no idea how to access it for the 3rd element.
Any help would be much appreciated.
Upvotes: 4
Views: 3051
Reputation: 37785
One way to move things out of your main controller is to share and make all changes to the data between controllers inside a service or factory (described pretty nicely in this article).
Here is an updated fiddle. You would just need to inject the itemsService
into any controller you would want to access the items data in.
angular.module('test', [])
.service('itemsService', function(){
var items = ['A', 'B', 'C', 'D'];
return{
getItems: function(){
return items;
},
changeItem: function(index, value){
items[index] = value;
}
}
})
.controller('MainCtrl', function($scope, itemsService) {
$scope.items = itemsService.getItems();
$scope.change = function(idx) {
itemsService.changeItem(idx, 'X');
}
})
Upvotes: 6