我有一项返回响应的服务。作为回应,我有用户数。我有一个 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/