Because of JavaScript's first-class functions, we have the ability to pass them around just like any other variable.
Take a look at this JSFiddle demonstration where clicking on Change Handler
switches between f1
and f2
.
HTML
<body ng-app="exampleApp" ng-controller="appCtrl">
<div>
<h3>{{name}}</h3>
<br>
<button type="button" class="btn btn-primary" ng-click="fun()">Show Name</button>
<button type="button" class="btn btn-primary" ng-click="changeClick()">
Change Handler
</button>
<br>
<h3 ng-show="clicked">You did it {{name}}</h3>
</div>
</body>
JavaScript
var app = angular.module('exampleApp', []);
app.controller('appCtrl', function($scope){
function f1() {
$scope.name = "Chris";
}
function f2() {
$scope.name = "Harry";
}
$scope.fun = f1;
$scope.changeClick = function() {
if($scope.fun === f1) {
$scope.fun = f2;
} else {
$scope.fun = f1;
}
};
$scope.name = "Default";
});
The snippet demonstrates how changeClick
flips the value of fun