AngularJS 1.2.0rc1 Focus & Blur Directives

AngularJS 1.2.0rc1 directives for blur and focus events.

by apinstein

HTML

<script src="http://code.angularjs.org/1.2.0rc1/angular.js"></script>
<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>

JavaScript

// 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 } );
}