Andzej Maciusovic
Andzej Maciusovic

Reputation: 4476

AngularJs allow digest only current scope

Question: I have two controllers Dog and Cat. If I change dog name then $digest cycle runs and Cat also update here view because of method {{ctrl.getTime()}} usage. This is a big problem for big applications which loads all controllers and don't use ng-if or state. In our current app we have a lot of places where we use methods inside templates and what is event worse we load and initialise all application controllers and don't use states or ng-if, we only use ng-show. I know what better solution is to use properties, but I wonder is it possible tell angular to $digest only DogCtrl scope instead of all app scopes?

HTML

<div ng-app="myApp">
    <div ng-controller="DogCtrl as ctrl">
        <h3>DogCtrl</h3>
        Dog name: <input ng-model="ctrl.name" />{{ctrl.name}}
    </div>
    <hr />
    <div ng-controller="CatCtrl as ctrl">
        <h3>CatCtrl</h3>
        Cat getTime: {{ctrl.getTime()}} {{ctrl.random}}
    </div>
</div>

Javascript

var myApp = angular.module('myApp',[]);
myApp.controller('DogCtrl', DogCtrl);
myApp.controller('CatCtrl', CatCtrl);

function DogCtrl() {
        this.name = 'Doggy';
}

function CatCtrl() {
        this.getTime = function() {
            return new Date().getTime();
    }
}

Fiddle: http://jsfiddle.net/nvgofo46/1/

Upvotes: 1

Views: 276

Answers (1)

Will
Will

Reputation: 1768

Change your html to this:

<div ng-controller="CatCtrl as ctrl">
    <h3>CatCtrl</h3>
    Cat getTime: {{ctrl.currentTime}} {{ctrl.random}}
</div>

And change your controller to this:

function CatCtrl() {
    this.getTime = function() {
      return new Date().getTime();
    }
    this.currentTime = this.getTime();
}

As a rule of thumb, try not to have functions in your view. Because the functions will execute on every digest. It's more efficient to bind to a model and update the model accordingly.

I could have remove the function and simply set this.currentTime = new Date().getTime(), but that's not the point of this exercise.

Upvotes: 1

Related Questions