javascriptangularjsangularjs-digestangularjs-ng-init

Angular JS - declaring function inside ng-init?


I have few queries. Pls find them below -

1) A function defined inside an ng-init like given below

ng-init='function a() {}'

errors out. Changing the syntax to variable declaration type or Instantly invoked also doesn't work. why? Since we can anyway declare a variable, object, array. Why not a function?

2) Is a $watch created for all variables tied to a scope, OR is it created to only those scope variables which are shown in the view?

3) If you run the fiddle 'http://jsfiddle.net/Lvc0u55v/5753/', there is >10 $digest iterations error. This is expected. Now please comment and uncomment as given in the fiddle. there is no error, how come? here also $scope.a's value changes infinitely right?


Solution

  • Let me try to get your questions answered.

    1) As far as I know ng-init is not supposed to work with function expressions. It's rather used to handle logical expressions. You may take a look into the docs, it's also pointed out there including a short example. So as the doc says:

    The ngInit directive allows you to evaluate an expression in the current scope.

    2) Generally a $watch is not tied up to each variable of a scope (even though it can be tied up to a whole digest cycle). As you've done in your example, you have bound $watch to your scopes variable called a. So it will trigger every time your $scope.a variable changes. You may also check the docs here too.

    3) Regarding this question, the answer is pretty simple. Let's assume we start with $scope.a = 10 (as you've already done). The moment you run your app your $watch will pretty much fire. Doing so, you'll get the following:

    nv = 10;
    ov = 10;
    $scope.a = ov * 9;
    

    Assuming that, you'r $scope.a will now be 90, which obviously will fire your watcher again. This time with the following:

    nv = 90;
    ov = 10;
    $scope.a = ov * 9;
    

    Now, at this point your new value is the same as it was before. At this rate your watcher won't fire again because the value doesn't change (since it's exactly the same as before).

    On the other hand, running $scope.a = nv * 9 would always update $scope.a and this will lead to an infinite loop.

    I hope this helps.