In my view I want to display a computed property multiple times, if I do {{ctrl.Compute()}}
multiple times, then compute function get called multiple times.
I have created this plunkr demo to simply my question http://plnkr.co/edit/TcMcJUipLKk94dthnivU
Controller
app.controller('MainController',function(){
var ctrl= this;
var list = [];
ctrl.count = function(){
console.log('Invoked');
return list.length
}
ctrl.add = function(){
list.push(1)
}
});
View
<body ng-controller="MainController as ctrl">
<button ng-click="ctrl.add()">Add</button>
<br>
List Size: {{ctrl.count()}} <br>
List Size: {{ctrl.count()}} <br>
List Size: {{ctrl.count()}} <br>
List Size: {{ctrl.count()}} <br>
</body>
In view, you can see I am calling {{ctrl.count()}}
four times and that means computation is happening four times. How can I do computation only once and display a value multiple times.?
Please don't suggest, ideas like, make array part of controller like ctrl.list
, then in view use {{ctrl.list.length}}
. This idea might for this eg but wont work where a complex computation is required.