I have this fiddle example where I am trying to set a value in an ng-repeat that lives in a different scope. This is a very basic example of a much bigger issue I am trying to solve. Basically I need to set a variable in the ng-repeat so that angular will update the template accordingly. The problem is that the template is in a child controller. So i use the $controller inject-able to access the variable. However, updating this variable does not cause the template to update. Even if I do a scope.$apply(). Anyone have any ideas? I am unsure on another way to do this...
var myApp = angular.module('myApp', []);
myApp.directive("custdirective", function() {
return {
restrict: 'A',
scope: 'false',
link: function(scope, element, attr) {
element.on("click", function() {
anotherscope.addList();
});
}
}
});
function AnotherController($scope) {
$scope.listtwo = new Array();
$scope.addList = function() {
$scope.listtwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
}
}
function MyCtrl($scope, $controller, $rootScope) {
anotherscope = $rootScope.$new();
$scope.anothercontroller = $controller(AnotherController, {
$scope: anotherscope
});
}
To do this correctly, one would create a service. I made an updated fiddle of the correct way to do this here or:
var myApp = angular.module('myApp', []);
myApp.factory("mySharedService", function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function() {
this.message = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
myApp.directive("custdirective", function() {
return {
restrict: 'A',
scope: 'false',
link: function(scope, element, attr) {
element.on("click", function() {
debugger;
scope.handleClick();
});
}
}
});
function AnotherController($scope, sharedService) {
$scope.listtwo = new Array();
$scope.addList = function() {
$scope.listtwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
}
$scope.$on('handleBroadcast', function() {
$scope.listtwo = sharedService.message;
$scope.$apply();
});
}
function MyCtrl($scope, sharedService) {
$scope.handleClick = function() {
sharedService.prepForBroadcast();
};
}
MyCtrl.$inject = ['$scope', 'mySharedService'];
AnotherController.$inject = ['$scope', 'mySharedService'];
Passing scopes around like that is a little wonky, and is almost guaranteed to break the testability of your Angular application.
I think you'd be better off creating a service that brokered changes between your controllers and your directive. The service would contain either the arrays you wished to update, or the functions you wished to call from your directive.
I'm afraid it's hard to write up an example of such a service, as I don't really understand what your ultimate goal is.