pidacrep
pidacrep

Reputation: 359

What causes a controller function to be called in Angular?

I'm going through Angular tutorials and seeing code like this:

todoApp.controller("ToDoCtrl", function($scope) {
    $scope.todo = model;

    $scope.warningLevel = function() {
        return $scope.incompleteCount() < 3 ? "label-success" : "label-warning";
    }
});

<span ng-class="warningLevel()">Tasks</span>

Like magic, the span changes its class whenever calling warningLevel() would return a new value. But the tutorials don't explain why. I don't understand how Angular "knows" that warningLevel() would return a new value and needs to be called again. What is triggering warningLevel() to be called each time?

Upvotes: 1

Views: 69

Answers (1)

DonJuwe
DonJuwe

Reputation: 4563

As @Linh Pham pointed out this is the so called Two-Way-Databinding. It works this way due to Angular's $digest cycle.

Processes all of the watchers of the current scope and its children. Because a watcher's listener can change the model, the $digest() keeps calling the watchers until no more listeners are firing.

You can imagine it as a static loop which watches for changes and updates the values within the respective $scope. You can also "hook" in to this cycle by binding$watchers manually e.g.:

$scope.$watch('myScopeVar', function() {
    // do something
});

Upvotes: 1

Related Questions