javascript - $watch 函数没有被触发

标签 javascript angularjs

我有一项返回响应的服务。作为回应,我有用户数。我有一个 var userCount 并且在这个 userCount var 上有一个 watch() 。

               var userCount=null;
          var eventPromise = userSer.load(query, deviceType,$scope.duration);
            eventPromise.then(function(response) {
                console.log(response)
                var dataLength = response.users.length;
                $scope.numberOfRecords = dataLength;

                if(dataLength > 0){                       
                   userCount = response.beaconCount;
                   setUserCount(userCount);
                  }

              var setUserCount=function(data){
            userCount=data;
        };
                var getUserCount=function(){
            return userCount;
           }

//这个 $watch 函数没有被触发,因为我们正在将 userCount 的值从 null 更改为 response.userCount。

            $scope.$watch(userCount, function(newVal){
            alert("M in watch func");

              $scope.gridOptions.columnDefs[0].displayName = 'Beacon(' + getUserCount() + ')';
              $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);


        })

最佳答案

你搞乱了 $scope.$watch 的用法,$scope.$watch 的正确用法如下,引用文档 here :

用法1:观察$scope所属变量的变化。

$scope.userCount = null;
$scope.$watch("userCount", function() { ... });

用法2:观察不属于 $scope 的变量的变化。

var userCount = null;
$scope.$watch(function() { return userCount; }, function() { ... });

引用下面的例子。

angular.module("app", [])
  .controller("myCtrl", function($scope, $timeout) {
    $scope.data = null;
    var data2 = null;
    
    $scope.$watch("data", function() {
      console.log("data change detected.");
    });
    
    $scope.$watch(function() { return data2; }, function() {
      console.log("data2 change detected.");
    });
    
    $timeout(function() {
      $scope.data = {id: 1};
      data2 = {id: 2};
    }, 2000);
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  
</div>

关于javascript - $watch 函数没有被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44587348/

相关文章:

javascript - 如何知道请求是使用 HTTP 1.x 还是 HTTP2 执行的

javascript - 如何根据变量值动态请求 React 组件?

javascript - Angular : Infinite scroll not working when using ngInclude in masonry

javascript - 在 angularjs 中创建自定义控件的推荐方法

javascript - AngularJS : index not updating after removing array item(s) by index

angularjs - ng-if,不等于?

javascript - Sencha 触摸2 : Creating a Nested List inside a tab panel

javascript - Reactjs onclick显示组件

javascript - Jquery - 使用 grep 搜索表的所有列?

angularjs - 取消绑定(bind) Angular 元素