Angularjs: accessing the inside from outside

I am trying to move bits from a parent controller inside child controllers to an angularjs application so as not to pollute the main controller too much. Here is a simplified fiddle: http://jsfiddle.net/terebentina/5RMPV/ Therefore, when I click the change button, the third letter should change to "X". Initially, the item_change () function was inside the main controller and executed $scope.items[idx] = 'X' , and that worked fine. However, since I moved it inside the ItemCtrl, I have no idea how to access it for the third item.

Any help would be greatly appreciated.

+4
source share
1 answer

One way to move things from your main controller is to exchange and make any changes to the data between the controllers inside the service or factory (described quite well in this article ).

Here is the updated script . You just need to inject the itemsService into any controller that you want to access the item data.

 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'); } }) 
+6
source

Source: https://habr.com/ru/post/1432980/


All Articles