Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS private variable in controller function

I am new to Angularjs. I came across a example online and it got me really confused. Here is the code:

angular.module("testApp",[]).controller("testCtrl", function($scope){

    var data = "Hello";

    $scope.getData = function(){
        return data;
    }

    $scope.setData = function(newData){
        data = newData;
    }
});

Here is the view:

<html ng-app = "testApp">
    <head>
        <script src="lib/Angular.js"></script>
        <script src = "foo.js"></script>
    </head>
    <body ng-controller="testCtrl">
        <div ng-click="setData('Hello Hello')">{{getData()}}</div>
    </body>
</html>

My question is how does angular know when to trigger the getData() method in the view. The click event will change the data. However its a private variable, not attaching to the $scope, which means $scope does not watch the change of it, then how does angular know when to call the getData() in the view? I know it maybe a dumb question, but please help! thank you so much!!

like image 514
Ryan.Gao Avatar asked Aug 29 '14 21:08

Ryan.Gao


2 Answers

The double-curly expression is what AngularJS calls an observing directive. During the compilation phase, this directive registers listeners on the expression using the $watch method of the scope.

On the other hand, ng-click is what AngularJS calls a listener directive. This type of directive registers a listener with the DOM instead. Whenever the DOM event fires, the directive executes the associated expression inside an $apply call.

This means that after the click expression is executed, a $digest cycle will begin. In this cycle, the scope examines all the registered $watch expressions (e.g. the double-curly expression containing getData()) and calls the listener in case there's a difference from the previous value.

In the end, it is this digest cycle that ensures that all your bound expressions are evaluated.

like image 138
Răzvan Mocanu Avatar answered Nov 05 '22 07:11

Răzvan Mocanu


The top level controller function runs immediately before it renders the view, in order to initialise the scope. Next the view loads and any logic in the view executes. So when it reaches getData() it returns the output of that function at that time.

The clever part is that Angular automatically binds the data in your views all the way back to the data model, so whenever there is a change in the model (i.e. the source of the data) that automatically updates the value in the view and if necessary will run your getData() method several times.

I saved it here as a Plnkr

like image 41
Ade Avatar answered Nov 05 '22 06:11

Ade