$ watch函数没有被触发

时间:2017-06-16 10:46:39

标签: 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);


        })

2 个答案:

答案 0 :(得分:1)

你不能$watch这样的任何变量。将userCount变量分配给$scope,它将起作用。

$scope.userCount = null;

userSer.load(query, deviceType, $scope.duration).then(function (response) {

    console.log(response);

    var dataLength = response.users.length;
    $scope.numberOfRecords = dataLength;

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

});

答案 1 :(得分:1)

您搞砸了dynamic _dockets; 的使用情况,$scope.$watch的正确用法如下所示,请参阅文档 here

用法1:观看变量的变化属于$scope.$watch

$scope

用法2:观看变量的变化不属于$scope.userCount = null; $scope.$watch("userCount", function() { ... });

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