It seems that when I use a service, called by a controller, within a directive, to update an array in the main controller (MyController in the example), Angular doesn't update the view.
However if I leave the service out, and have the directive directly update the array, then the view is updated.
(In the example below I have, in MyDirectivesController there are 2 lines, one commented out which is the version that works - changing gridInDirective directly....the line below it calls myService, which does get the gridInDirective array locally, and does seem to change it locally, but the view is not updated)
If you run the example the idea is that you click on the colored div and the elements of the array, printed by the ng-repeat loop, are changed.
I have experimented with using $scope.$apply() in a few places but (a) didn't work and (b) my understanding is that that should only be necessary if I am making changes outside of Angular...and I don't think I am.
So the question is, how do I get the version of the grid that is updated in myService to update the view, and also why doesn't it work the way I have it?
Thanks in advance to anyone who takes the time to have a look.
'use strict';
(function() {
var ssheet = angular.module('ssheet', []);
ssheet.factory('myService', [function () {
var myServiceFunction;
return {
myServiceFunction: function (grid) {
alert('myServiceFunction');
alert('grid given to myServiceFunction is ' + grid.toString());
grid = ['now', 'the', 'grid', 'has', 'changed'];
alert('grid in myServiceFunction changed to ' + grid.toString());
}
}
}]);
ssheet.controller('MyController', ['$scope', function ($scope) {
$scope.gridInMyController = ['foo','bar','dog','cat']; // this was a 2D array, but simplified it for testing
}]);
ssheet.controller('MyDirectivesController', ['myService', '$scope', function (myService, $scope) {
$scope.changeGrid = function () {
alert('MyDirectivesController.changeGrid');
//$scope.gridInDirective = ['now', 'the', 'grid', 'has', 'changed']; //this worked
myService.myServiceFunction($scope.gridInDirective); // this doesn't work
}
}]);
ssheet.directive('gridTools', ['myService', function (myService) {
return {
restrict: 'E',
replace: true,
scope: {
gridInDirective: '=gridInElement',
},
template: '<div class="grid-tools-style" grid-in-element="gridInMyController" ng-click="changeGrid()">Click this div to change the grid</div>',
controller: 'MyDirectivesController',
}
}]);
})();
.grid-tools-style {
background-color: #c68700;
}
.grid-tools-style:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ssheet">
<div ng-controller="MyController">
<grid-tools></grid-tools>
<div ng-repeat="item in gridInMyController"><p>{{item}}</p></div>
</div>
</body>