0
我正在使用服务来更改某个范围A的变量。当我尝试$watch
对这些变量的更改时,什么都不会发生。
基本设置如下所示。我想在我自己的定制指令中使用$watch
,我将它添加到元素中。但是,如果这是不可能的,我至少会喜欢从控制器内部使用$watch
。我发了一个plunkr here。正如你可以看到$scope.someVar
的变化,但$ watch永远不会在控制器或指令中被触发。
app.factory("changerService", function() {
var $scope;
function change(to) {
$scope.someVar = to;
}
function setScope(scope) {
$scope = scope;
}
return {
Change: change,
SetScope: setScope
}
});
app.controller("bar", ["$scope", "changerService", function ($scope, changerService) {
$scope.someVar = true;
changerService.SetScope($scope);
$scope.showImg = function (val) {
changerService.Change(val);
$scope.state = $scope.someVar;
};
$scope.$watch($scope.someVar, function (newVal, oldVal) {
$scope.watchController = newVal ? newVal : "undefined";
});
}]);
app.directive("myDirective", function() {
return {
link: function (scope, element, attrs) {
scope.$watch(scope.someVar, function (newVal, oldVal) {
scope.watchDirective = newVal ? newVal : "undefined";
});
}
}
});
完美!谢谢 – user1873073