Ram_T
Ram_T

Reputation: 8484

Scope function calling on DOM change(two-way data binding) angularjs

<!DOCTYPE html>
<html data-ng-app="app">

<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>

<body data-ng-controller="SimpleController">
  <script>
    var app = angular.module('app', []);
    app.controller('SimpleController', SimpleController);

    function SimpleController($scope) {
      $scope.isNumberA = function(val) {
        console.log('called');
        if (val == 2) return true;
      }
    }
  </script>
  <input type="checkbox" ng-model="switcher" />
  <h1 ng-if="isNumberA(10)">isNumber</h1>

</body>

</html>

In the above code first time, isNumberA calling because of ng-if="isNumberA(10)" but I don't know why it is calling another time. Check console, it prints two times on DOM render in brower. After that when I click on check box again it calling the function. Why this method calling on check box click? I didn't called it. Is this the two-way binding? And also if I remove the <h1 ng-if="isNumberA(10)"></h1>, it is not calling. What is happening here?

Upvotes: 2

Views: 802

Answers (2)

pankaj sharma
pankaj sharma

Reputation: 286

You have used a function call rather then a variable for condition (ng-if). Angular watch every scope variable used in view, but when you use a function call, it can't decided which variable or event will effect this function return value, so Angular run such function on every digest cycle. You should call this function in ng-init and store the return value of this function in a variable, and use that variable in ng-if.

$scope.isNumberA = function(val) {
    console.log('called');
    if (val == 2){
        $scope.showIfBlock = true;
    } else {
        $scope.showIfBlock = false;
    }
  }


<span ng-init="isNumberA(10)"></sapn>
<h1 ng-if="showIfBlock">isNumber</h1>

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222582

ng-if will evaluate its expression when digest cycle runs, basically you shouldn't make an function call from ng-if expression.

DEMO

<!DOCTYPE html>
<html data-ng-app="app">
<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body data-ng-controller="SimpleController">
  <script>
    var app = angular.module('app', []);
    app.controller('SimpleController', SimpleController);
    function SimpleController($scope) {
      $scope.isNumberA = function(val) {
        console.log('called');
        if (val == 2) $scope.block = true;
        $scope.block = false;
      }
    }
  </script>
  <input type="checkbox" ng-model="switcher" />
  <span ng-init="isNumberA(10)"></sapn>
   <h1 ng-if="block">isNumber</h1> 
</body>
</html>

Read More here

ng-if being called more times than it should

Upvotes: 1

Related Questions