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")
}
3
  • 1
    You can pass the function reference to your event handler and that way not bother about this. Commented Jun 29, 2016 at 8: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. Commented Jun 29, 2016 at 8: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 Commented Jun 29, 2016 at 12:14

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Implemented it after moving the deleteRequirement function to $scope. TY

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.