如何监视$ scope变量从控制器

时间:2016-06-16 09:41:06

标签: javascript angularjs

我希望在我的$scope.count从控制器自身更改时运行一些代码。我尝试使用$scope.$watch函数但仅检测不到它。 fiddel HTML:

See your console
<div ng-controller="MyCtrl2">
   <p>
    Count : {{greeting}}
   </p>
</div>

我的JS:

function MyCtrl2($scope) {
  $scope.count = 0;

  $scope.$watch("count", function(newValue, oldValue) {
    $scope.greeting = $scope.count;
  });

 window.setInterval(function(){ 
    $scope.count++; 
    console.log('$scope.count : '+$scope.count);
 }, 1000);

}

4 个答案:

答案 0 :(得分:2)

我能想到的一种方式是广播变化,然后收听这样的广播。这可能是一个相对便宜的选择。

例如:在进行更改后,您将更改计数的位置进行广播:

//在代码中修改了计数

$rootScope.$broadcast('count-changed');

然后你可以在需要的地方听它:

$scope.$on('count-changed', function(event, args) {

    // do what you want to do
});

答案 1 :(得分:1)

您需要使用angular $interval服务而不是setInterval来获取角度,以便能够跟踪变更后的变量。

尝试:

function MyCtrl2($scope, $interval) {
  $scope.count = 0;

  $scope.$watch("count", function(newValue, oldValue) {
    $scope.greeting = $scope.count;
  });

 $interval(function(){ 
    $scope.count++; 
    console.log('$scope.count : '+$scope.count);
 }, 1000);

}

答案 2 :(得分:1)

$scope.$apply()用作here

您正在使用不会调用摘要周期的setInterval,或者您可以使用angular的$ interval()

function MyCtrl2($scope) {
  $scope.count = 0;

  $scope.$watch("count", function(newValue, oldValue) {
      $scope.greeting = $scope.count;
  });

  window.setInterval(function(){ 
            $scope.count++; 
        console.log('$scope.count : '+$scope.count);
       $scope.$apply()
  }, 1000);

}

答案 3 :(得分:1)

使用$scope.$apply

  window.setInterval(function(){ 
            $scope.count++; 
        console.log('$scope.count1 : '+$scope.count);
        $scope.greeting = $scope.count;
        $scope.$apply();
  }, 1000);
相关问题