ReynierPM
ReynierPM

Reputation: 18660

Prevent $watch to be called if element is not changed

I have this code in my Angular controller:

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");
                }
            });
        });
    }]);

Any time I load the page the updStatus is called twice, so how I prevent the $watch to be executed and just call the function when the ng-model="updStates" changes? I have the same behavior with other controllers, I miss something at $watch docs? It's not supposed that this will only works if ng-model changes?

Upvotes: 0

Views: 75

Answers (2)

Chris
Chris

Reputation: 17535

If you're using an ng-model it's usually easier to use the ng-change directive instead of $watch:

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

Every time foo changes your fooChanged() function will be called.

Upvotes: 2

dfsq
dfsq

Reputation: 193261

Usually you put a check inside of the watch comparing previous an current value:

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

Upvotes: 0

Related Questions