0
               <div class="category">
                  <div ng-dropdown-multiselect="" options="categories" selected-model="selectedCategories" extra-settings="categoriesSettings" translation-texts="customTexts"></div>
                </div>

  $scope.$watch('selectedCategories', function(newValue, oldValue){
    console.log(newValue);
    console.log(oldValue);
    $scope.loadPosts();
  }, true);

  $scope.$watch('selectedCities', function(newValue, oldValue) {
    console.log(newValue);
    console.log(oldValue);
    $scope.loadPosts();
  }, true);

These two watches have been triggered when the page is initially loaded. Isn't it supposed not to trigger when the page is loading and the array not being changed?

2 Answers 2

1

That's correct watcher's behavior. Adding if (angular.equals(newValue, oldValue)) { return; } inside callback will solve your issue.

Sign up to request clarification or add additional context in comments.

Comments

1

From the Angular Docs (just before the first example)

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.

You could check if newValue !== oldValue to prevent it or create a variable that prevents the first check.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.