Consider the following code
<body ng-app="myApp">
<h1>Hello {{name}}</h1>
<h2>reverse of your name is {{ name | reverse }}</h2>
<input type="text" ng-model="name">
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.js'></script>
<script>
angular.module('myApp', [])
.filter('reverse', function(){
return function(str){
return str.split('').reverse().join('');
}
});
</script>
</body>
The interested bit here is the reverse filter. Here is what I think its doing:
- calls
angular.filter()with two args.arg1: string &arg2: function(anonymous or no-name function to be precise) - arg2 function doesn't take a argument and instead nested another anonymous function inside it.
- This nested anonymous function does takes single argument - the text or string on which this filter would apply.
- this nested anonymous function takes the string, reverses it.
Q1. Is my understanding correct?
Q2. What the difference between: normal version:
angular.filter('reverse', function(str){
return str.split('').reverse().join('');
});
nested version:
angular.filter('reverse', function(str){
return function(str){
return str.split('').reverse().join('');
}
});
Q3. Why is extra level of function nesting useful & under what circumstances will I return the value directly. Or return a function which then does return the actuall result?
Q4. How does this affects scope? does closures have any role to play here?
JSFiddle: http://jsfiddle.net/C7EDv/