Angular+JQ+Bootstrap
clean code to understand event binding in angularjs
by de Montalembert Jonathan
HTML
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js"></script>
<div ng-controller="MyCtrl">
<h3>detect key in controller</h3>
<input on-keyup-fn="handleKeypress">
<br />Key Log: {{keylog}}
<hr />
<h3>detect key in directive</h3>
<!--27,13 = escape, enter-->
<input on-keyup="keyCount = keyCount+1" keys="[27,13]">
<br />Times escape or enter pressed: {{keyCount}}
</div>
JavaScript
var app=angular.module('myApp', []);
app.directive('onKeyupFn', function() {
return function(scope, elm, attrs) {
//Evaluate the variable that was passed
//In this case we're just passing a variable that points
//to a function we'll call each keyup
var keyupFn = scope.$eval(attrs.onKeyupFn);
elm.bind('keyup', function(evt) {
//$apply makes sure that angular knows
//we're changing something
scope.$apply(function() {
console.log(scope)
keyupFn.call(scope, evt.which);
});
});
};
});
app.directive('onKeyup', function() {
return function(scope, elm, attrs) {
function applyKeyup() {
scope.$apply(attrs.onKeyup);
};
var allowedKeys = scope.$eval(attrs.keys);
console.log(allowedKeys)
elm.bind('keyup', function(evt) {
//if no key restriction specified, always fire
if (!allowedKeys || allowedKeys.length == 0) {
applyKeyup();
} else {
angular.forEach(allowedKeys, function(key) {
if (key == evt.which) {
applyKeyup();
}
});
}
});
};
});
function MyCtrl($scope) {
$scope.keylog = [];
$scope.keyCount= 0;
$scope.handleKeypress = function(key) {
console.log('d')
$scope.keylog.push(key);
};
}