如果元素未更改,则阻止调用$ watch

时间:2014-03-21 18:43:40

标签: javascript angularjs

我在Angular控制器中有这个代码:

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 docs错过了什么?不应该只在ng模型发生变化时这才会起作用吗?

2 个答案:

答案 0 :(得分:2)

如果您使用ng-model,通常更容易使用ng-change指令而不是$watch

<input ng-model="foo" ng-change="fooChanged()"/>

每次foo更改时,您的fooChanged()功能都会被调用。

答案 1 :(得分:0)

通常你会在手表内部检查以前的当前值:

$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");
            }
        });
    }
});
相关问题