"Computed Properties" in AngularJS -
i chose angularjs on ember.js project working on, , have been pleased far. 1 nice thing ember built in support "computed properties" automatic data binding. have been able accomplish similar in angular code below, not sure if best way so.
// controller angular.module('mathskills.controller', []) .controller('nav', ['navigation', '$scope', function (navigation, $scope) { // "computed property" $scope.$watch(navigation.getcurrentpagenumber, function(newval, oldval, scope) { scope.currentpagenumber = newval; }); $scope.totalpages = navigation.gettotalpages(); }]); // 'navigation' service angular.module('mathskills.services', []) .factory('navigation', function() { var currentpage = 0, pages = []; return { getcurrentpagenumber: function() { return currentpage + 1; }, gettotalpages: function() { return pages.length; } }; }); // html template <div id=problempager ng-controller=nav> problem {{currentpagenumber}} of {{totalpages}} </div>
i ui update whenever currentpage
of navigation
service changes, above code accomplishes.
is best way solve problem in angularjs? there (significant) performance implications using $watch()
this? better accomplished using custom events , $emit()
or $broadcast()
?
while self-answer works, doesn't implement computed properties. solved problem calling function in binding force binding greedy. i'm not 100% sure it'd work in cases, , greediness might have unwanted performance characteristics in situations.
i worked solution computed properties w/dependencies similar emberjs has:
function ngcreatecomputedproperty($scope, computedpropertyname, dependentproperties, f) { function assignf($scope) { var computedval = f($scope); $scope[computedpropertyname] = computedval; }; $scope.$watchcollection(dependentproperties, function(newval, oldval, $scope) { assignf($scope); }); assignf($scope); }; // in controller... ngcreatecomputedproperty($scope, 'asquared', 'a', function($scope) { return $scope.a * $scope.a } ); ngcreatecomputedproperty($scope, 'aplusb', '[a,b]', function($scope) { return $scope.a + $scope.b } );
see live: http://jsfiddle.net/apinstein/2kr2c/3/
it's worth noting $scope.$watchcollection efficient -- verified "assignf()" called once if multiple dependencies changed simultaneously (same $apply cycle). "
Comments
Post a Comment