Last active
December 24, 2015 20:29
-
-
Save apinstein/6858299 to your computer and use it in GitHub Desktop.
AngularJS: how to do Ember-style computed properties in angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// do it live: http://jsfiddle.net/apinstein/2kR2c/1/ | |
// in DOM | |
<div ng-controller="MyCtrl"> | |
<p ng-click="bumpA()">a: {{a}}</p> | |
<p ng-click="bumpB()">b: {{b}}</p> | |
<p>a^2 = {{aSquared}}</p> | |
<p>a + b = {{aPlusB}}</p> | |
</div> | |
// requires angular 1.1.4+ (due to $watchCollection) | |
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); | |
}; | |
var myApp = angular.module('myApp',[]); | |
function MyCtrl($scope) { | |
$scope.a = 1; | |
$scope.b = 10; | |
$scope.bumpA = function() { $scope.a++ }; | |
$scope.bumpB = function() { $scope.b++ }; | |
ngCreateComputedProperty($scope, 'aSquared', 'a', function($scope) { return $scope.a * $scope.a } ); | |
ngCreateComputedProperty($scope, 'aPlusB', '[a,b]', function($scope) { return $scope.a + $scope.b } ); | |
} | |
// once happy, post to here: http://stackoverflow.com/questions/11216651/computed-properties-in-angular-js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment