1

I have a very simple app where I'm trying to call my controller's function like below

 var app=angular.module('test',[])
 app.controller('ctrl',function($scope){
 $scope.func=function(){
    alert('hi')
  }
})

This is how I'm calling it

  <body ng-app='test' >
    <h1 ng-controller='ctrl'>{{func()}}</h1>

  </body>

The problem which I'm facing is my function is getting called twice.

Read many posts on SO where the reason behind this issue is mostly related to your app configuration or route configuration where by mistake if you have configured same controller for different view or if your app is getting initialized twice then you will face this issue.

But in my case I don't have any such cases but still I'm facing this issue.

Rishi Tiwari
  • 1,041
  • 1
  • 10
  • 20

2 Answers2

3

Using {{func()}}, you are creating watch on the function func, every time digest cycle runs, func will be invoked.

A demo to demonstrate:

var app = angular.module('test', [])
app.controller('ctrl', function($scope) {
  $scope.val = 100;
  $scope.func = function() {
    alert($scope.val)
  };
  $scope.add = function(a) {
    return ++$scope.val;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>

<body ng-app='test'>
  <h1 ng-controller='ctrl'>
    {{func()}}
    {{add()}}
  </h1> 
</body>

Fiddle demo to play with

Rayon
  • 36,219
  • 4
  • 49
  • 76
  • @RishiTiwari, It is like applying watch over `$scope.val` – Rayon Jun 28 '16 at 05:11
  • I don't have any $scope.val..I just have a func() on $scope...In your example you are changing the value of "val" everytime that is why the digest cycle is getting executed multiple times and that too only for 10 times also you will get exception in as it has created an infine loop... – Rishi Tiwari Jun 28 '16 at 05:15
  • @RishiTiwari, Dude the demo is to demonstrate.. Digest cycle has many things to re-run it.. I have explained you only one..Exceptions is quiet obvious..That is why I have highlighted it.. – Rayon Jun 28 '16 at 05:17
  • When your digest cycle runs it actually runs your wacthes...so in this case if the function is getting called twice just because of the digest cycle my watch on that function should also get called twice. – Rishi Tiwari Jun 28 '16 at 05:25
  • @RishiTiwari, There are many watchers in angular directives which are hidden from you.. They are making the difference here... – Rayon Jun 28 '16 at 05:27
0

What is the purpose of func()?

Would it be possible to bind a variable instead of calling the function directly?

var app=angular.module('test',[])
 app.controller('ctrl',function($scope) {
   function func() { // called in the future
     $scope.funcValue = 'My Title';
   }
})

HTML:

<body ng-app='test' >
    <h1 ng-controller='ctrl'>{{ funcValue }}</h1>
</body>
Nailbite
  • 201
  • 1
  • 2
  • 5