AngularJS pass string as function to use at ng-click

KIC picture KIC · Feb 16, 2015 · Viewed 36.5k times · Source

I want to assign a javascript function to ng-click which name is sourced by a rest service.

<li ng-class="{ active: isActive('url')}" data-ng-repeat="menu in mb.data">
   <a href="{{menu.href}}" data-ng-click="{{menu.javascript}}">{{menu.label}}</a>
</li>

Sadly the angularjs parser throws an exception if one use {{ }} inside of ng-click. So I have tried several workarounds like using a callback function

  <a href="{{menu.href}}" data-ng-click="call(menu.javascript)">{{menu.label}}</a>

But none of my ideas succeeded. How can I assign a javascript functions name in ng-lick? Btw. the function itself is part of the $scope.

Edit- Here is the controller:

The "$menu" service is simply a get rest request. The request result is a json object and only holding string values. In the current issue the result for menu.javascript is "loginModal()".

.controller('HeaderController', function($scope, $http, ModalService, $menu, $routeParams) {
    $scope.loginModal = function() {
        console.log("modal", ModalService);
        // Just provide a template url, a controller and call 'showModal'.
        ModalService.showModal({
            templateUrl: "/modals/login.modal.html",
            controller: "LoginController"
        }).then(function(modal) {
            // The modal object has the element built, if this is a bootstrap modal
            // you can call 'modal' to show it, if it's a custom modal just show or hide
            // it as you need to.
            console.log(modal.element);
            modal.element.modal();
            modal.close.then(function(result) {
                console.log(result ? "You said Yes" : "You said No");
            });
        });
    };

    $menu.get($routeParams, function(data){
        $scope.menu = data;
    });
})

Edit 2:

Interestingly when I use {{menu.javascript}} then the correct string "loginModal()" is available in the DOM. But the angular parser stopped there due to errors.

Answer

Pankaj Parkar picture Pankaj Parkar · Feb 16, 2015

You can do something like this

HTML

  <div ng-controller="TodoCtrl">
      <button ng-click="callFunction('testClick')">CLICK ME</button>
  </div>

Controller

function TodoCtrl($scope) {

    $scope.callFunction = function (name){
        if(angular.isFunction($scope[name]))
           $scope[name]();
    }

    $scope.testClick = function(){
        alert("Called");
    }
}

Working Fiddle

Hope this could help you. Thanks.