Sr.Richie
Sr.Richie

Reputation: 5740

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?

Upvotes: 0

Views: 117

Answers (2)

Shivaraj
Shivaraj

Reputation: 613

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!

Upvotes: 1

Brocco
Brocco

Reputation: 64843

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;
};

Upvotes: 4

Related Questions