更改服务中的范围变量时,$ watch不起作用

时间:2014-03-24 18:47:55

标签: angularjs

我正在使用服务来更改范围A的一些变量。当我尝试$watch对这些变量进行更改时,没有任何反应。

基本设置如下所示。我想在我添加到元素的自定义指令中使用$watch。但如果这是不可能的,我至少希望能够在控制器内部使用$watch

我做了plunkr here。正如您可以看到$scope.someVar更改但是$ watch永远不会在控制器或指令上触发。

enter image description here

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";
            });
        }
    }
});

1 个答案:

答案 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";
            });
        }
    }
});