我正在使用服务来更改范围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";
});
}
}
});
答案 0 :(得分:1)
检查完代码后,我发现你的监视表达式是一个对象,但它必须是一个字符串。
示例:
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("someVar", function (newVal, oldVal) {
$scope.watchController = newVal ? newVal : "undefined";
});
}]);
app.directive("myDirective", function () {
return {
link: function (scope, element, attrs) {
scope.$watch("someVar", function (newVal, oldVal) {
scope.watchDirective = newVal ? newVal : "undefined";
});
}
}
});