How to display same computed value multiple times in AngularJs view by calling compute function only once -


in view want display computed property multiple times, if {{ctrl.compute()}} multiple times, compute function called multiple times.

i have created plunkr demo 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 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, can see calling {{ctrl.count()}} 4 times , means computation happening 4 times. how can computation once , display value multiple times.?


please don't suggest, ideas like, make array part of controller ctrl.list, in view use {{ctrl.list.length}}. idea might eg wont work complex computation required.

maybe this:

var savedcount = ctrl.count(); ctrl.count = function(){     console.log('invoked');     return list.length }  $scope.$watch("list", function() {savedcount = ctrl.count()}); 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -