0

In my AngularJS controller I have an event handler which receives an argument. The argument has a method name as string, which I need to execute. How do I call the method in my controller?

I have seen this question & answer but it doesn't work for me on the controller. Here is my code

The event is created by a directive which is a confirmation dialog. Event fires when the user clicks Yes.

app.directive('yesNoModal', function() {
  return {
    restrict: 'E',
    scope: {
        yesNoData: '=',
    },
    controller: function($scope) {
        $scope.handleYes = function() {
            $scope.$emit('clickedYes', { "yesNoData": $scope.yesNoData  });
        }
        $scope.handleNo = function() {
            $scope.$emit('clickedNo');
        }
    },
    templateUrl: 'partials/templates/yes-no-modal.html',
  }
})

Event handler

$scope.$on('clickedYes', function(event, arg) {
    console.log(arg)
    window[arg.yesNoData.yesMethod]()
});

window[arg.yesNoData.yesMethod] returns undefined in my case. I also tried with $window but I get undefined for the same. The function with the name of value of arg.yesNoData.yesMethod variable is defined in the controller as a method and the value of yesNoData is set before the modal is loaded. On clicking Yes in the modal the event is handled

function deleteRequirement() {
    console.log("In delete requirement")
}
Community
  • 1
  • 1
Dhanush Gopinath
  • 5,652
  • 6
  • 37
  • 68
  • 1
    You can pass the function reference to your event handler and that way not bother about this. – Rosmarine Popcorn Jun 29 '16 at 08:32
  • 1
    If it's the name of a method of some object (such as a scope) you need to access it through that object not through window. But best to do as @Burimi says and just pass a function around rather than a string. – Duncan Jun 29 '16 at 08:35
  • The function was not defined within the scope, so I thought I could call it. I moved it to the $scope and implemented Anubhav's solution. Thanks You – Dhanush Gopinath Jun 29 '16 at 12:14

1 Answers1

1

Use $scope[arg.yesNoData.yesMethod]() instead of window[arg.yesNoData.yesMethod]() since it is a method inside the $scope object and not the window object

Anubhav
  • 7,138
  • 5
  • 21
  • 33