How To Dynamically Bind Function To Ng-click Using The Function Expression From Model
I have the following element in my Angular template to generate a button bar with Font Awesome icons:
$parse
and do something like this.app.controller('MainCtrl',['$scope', '$parse', function($scope, $parse) { //<-- inject parse//.. Some code//Make this as handler to ngClick passing expression which is function name you have in your model$scope.callFunc = function(exp){
$parse(exp)($scope); //Parse the function name to get the expression and invoke it on the scope
}
//Your specific function to be called$scope.less = function(){
console.log('less');
}
$scope.more = function(){
console.log('more');
}
In your view do:-
data-ng-click="callFunc(btn[1])"
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $parse) {
$scope.navigation = {buttonBar:[
[ "fa-minus", "less()", "Show fewer cloud buttons." ],
[ "fa-plus", "more()", "Show more cloud buttons." ],
[ "fa-minus-square", "smaller()", "Make cloud buttons smaller." ],
[ "fa-plus-square", "bigger()", "Make cloud buttons bigger." ],
[ "fa-bars", "toggleShowStrings()", "Toggle display of matching strings." ],
[ "fa-refresh", "initialize();", "Load more content." ],
[ "fa-undo", "resetQuery()", "Clear query." ]
]};
$scope.callFunc = function(exp){
$parse(exp)($scope);
}
$scope.less = function(){
console.log('less');
}
$scope.more = function(){
console.log('more');
}
});
<linkdata-require="bootstrap-css@*"data-semver="3.2.0"href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" /><script>document.write('<base href="' + document.location + '" />');</script><linkhref="style.css" /><scriptdata-require="angular.js@1.2.x"src="https://code.angularjs.org/1.2.25/angular.js"data-semver="1.2.25"></script><divng-app="plunker"ng-controller="MainCtrl"><i>Click the first 2 buttons and check the console</i><ul><lidata-ng-repeat="btn in navigation.buttonBar"data-ng-click="callFunc(btn[1])"class="btn btn-default"style="font-size: 30px; vertical-align: middle;"tooltip-placement="bottom"tooltip="{{ btn[2] }}"
><iclass="fa {{ btn[0] }}"></i></li></ul></div>
Post a Comment for "How To Dynamically Bind Function To Ng-click Using The Function Expression From Model"