我有这个小提琴示例,我试图在不同范围内的 ng-repeat 中设置一个值。这是我试图解决的一个更大问题的一个非常基本的例子。基本上我需要在 ng-repeat 中设置一个变量,以便 Angular 相应地更新模板。问题是模板在子控制器中。所以我使用 $controller injection-able 来访问变量。但是,更新此变量不会导致模板更新。即使我做了一个 scope.$apply()。有人有想法么?我不确定另一种方法可以做到这一点......
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
});
}
要正确执行此操作,需要创建一项服务。我在这里更新了正确的方法,或者:
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'];