简体   繁体   中英

Doubts about data binding in AngularJS

I'm learning AngularJS by doing my first app with it. As far as now, everything was working ok and I'm pretty excited :)

But now I have a console.log that is totally confusing me, and I'm start thinking I've completely missed something.

I have a simple tag bound to a controller:

<h2 ng-controller='HeaderController' ng-show='data.actualSection > 0'>
    {{titleForSection()}}
</h2>

The controller is very simple:

    uxctModule.controller ('HeaderController', function ($scope, ModelData){
    $scope.data = ModelData;

    $scope.titleForSection = function () {
        console.log ("RETURNING IT");
        return ("I SHOULD RETURN YOU SOMETHING");
    }
});

What's really confusing me is that I've noticed that every time something is changing in the model, the function is triggered. How can the controller be executing the function constantly without a $watch in it?

Data binding in angular is done via a digest loop, which means that angular loops over and over again checking for changes, and in the case of a function that is bound to the function must be evaluated looking for changes.

This is the reason it is generally a bad idea to bind your UI to the result of a function. Instead you should do something like this:

Markup:

<h2 ng-controller='HeaderController' ng-show='data.actualSection > 0'>
    {{sectionTitle}}
</h2>

Controller:

$scope.sectionTitle = 'I SHOULD RETURN YOU SOMETHING';
//and update it dynamically
$scope.funcToUpdateTitle = function(newTitle){
    $scope.sectionTitle = newTitle;
};

Actually in angularJS all functions related to view will be called as and when a digest cycle is called in that way since you have called titleForSection() in your HTML so when where an event occurs in the HTML, causes the function to be executed.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM