Javascript 如果元素未更改,则防止调用$watch
我的角度控制器中有以下代码:Javascript 如果元素未更改,则防止调用$watch,javascript,angularjs,Javascript,Angularjs,我的角度控制器中有以下代码: app.controller('CompaniesView', ['$scope', '$http', '$location', '$routeParams', '$route', 'noty', function($scope, $http, $location, $routeParams, $route, $noty) { var id = ""; if ($routeParams.id !== undefined) {
app.controller('CompaniesView', ['$scope', '$http', '$location', '$routeParams', '$route', 'noty', function($scope, $http, $location, $routeParams, $route, $noty) {
var id = "";
if ($routeParams.id !== undefined) {
id = '/' + $routeParams.id;
}
$http.get(Routing.generate('company-info') + id).success(function(data) {
if (data.message) {
$noty.error(data.message);
} else {
$scope.company = data.company;
$scope.status = data.status;
$scope.updStatus = $scope.company.status;
$scope.orderProp = 'name';
}
}).error(function(data, status, headers, config) {
if (status == '500') {
$noty.error("No hay conexión con el servidor");
}
});
$scope.$watch("updStatus", function() {
$http.post(Routing.generate('updateCompanyStatus'), {
'newStatus': $scope.updStatus
}).success(function(data) {
if (data.message) {
$noty.error(data.message);
}
}).error(function(data, status, headers, config) {
if (status == '500') {
$noty.error("No hay conexión con el servidor");
}
});
});
}]);
每当我加载页面时,
updStatus
会被调用两次,那么我如何防止执行$watch
,并在ng model=“updStates”
更改时调用该函数呢?我与其他控制器的行为相同,我错过了$watch
文档中的某些内容?这并不是说只有ng型号发生变化时,此功能才会起作用?通常,您会在手表内部进行检查,比较之前的数值和当前值:
$scope.$watch("updStatus", function(newVal, oldVal) {
if (newVal != oldVal) {
$http.post(Routing.generate('updateCompanyStatus'), {
'newStatus': $scope.updStatus
}).success(function (data) {
if (data.message) {
$noty.error(data.message);
}
}).error(function (data, status, headers, config) {
if (status == '500') {
$noty.error("No hay conexión con el servidor");
}
});
}
});
如果您使用的是
ng型号
,通常使用ng change
指令而不是$watch
:
<input ng-model="foo" ng-change="fooChanged()"/>
每次
foo
更改时,您的fooChanged()
函数都会被调用。我可能会使用ng change
而不是$watch
@Chris您能写一个小例子吗?我从未使用过ng change
,
将在您的范围内调用fooChanged()
,只要ng model
项changes@Chris谢谢,如果您回答问题并接受您的解决方案,那就好了