Reputation: 461
I've discovered that when I use ng-include
it gets called far too often.
Every time you click one of the Nothing
buttons or change Views, or type something in the input box, getView
gets run several times. Up to 6 times when changing views. Basically doing anything that alters the $scope
will generate a call to getView
.
I've created a plunker to show the behavior I'm describing: plnkr.co
Is this normal behavior and is there any way to make it only run once? I'm worried I may be losing performance due to this.
MY CODE:
index.html
<body ng-app="includeExample">
<div ng-controller="ExampleController">
<div class="row">
<input type="text" ng-model="unrelated">
</div>
<div class="row">
<tabset>
<tab heading="View 1">
<ng-include src="getView('template1')"></ng-include>
</tab>
<tab heading="View 2">
<ng-include src="getView('template2')"></ng-include>
</tab>
</tabset>
</div>
</div>
</body>
Script.js
angular.module('includeExample', ['ngAnimate', 'ui.bootstrap'])
.controller('ExampleController', ['$scope',
function($scope) {
$scope.getView = function(filename) {
console.log("getView " + new Date());
return filename + ".html";
};
}
]);
Template1.html
Content of template1.html
<button type="button" class="btn btn-primary" ng-click="">Nothing</button>
Upvotes: 1
Views: 616
Reputation: 1335
Yeah, angularJS will go through getView()
every time you do anything. A good first iteration would be to assign it to a json object instead of using a get
method. Actually, it's better if you don't use any get
type methods in the html. Then if you really want it to not change, you can remove the 2 way binding (Render value without data-binding).
Upvotes: 1
Reputation: 10430
Angular is calling your getView
method each time a digest runs to make sure the value hasn't changed. This is part of the "magic" for how angular binds the model and the view together. If you look at the network tab for your development tools you will see that the template is not actually being retrieved by the browser each time the digest runs. Knowing that this is how the digest actually works - you should develop code accordingly running intensive operations in methods that are not directly bound to the view!
For more information on the digest itself see:
Hope that helps!
Upvotes: 3