AngularJS ng-click: how to call a function with a function as a parameter?

I want to code a function-confirmation-window (modal opens) called in ng-click directive.

Within this confirmation modality, there are two buttons: Cancel + Ok. Clicking on Cancel cancels the modal. Clicking on Ok should trigger the callback function defined through my ng-click call (with parameters):

<button ng-click="confirmBox('beSureQuestion', functionToCallWhenOkClicked(parameter))">Delete</button>

      

Is there a way to give the function as a parameter inside ng-click?

I don't want to use if-statements inside my html template.

Any suggestions?

+3


source to share


2 answers


No, you can do it the way you are trying to do it. The problem is that ngClick will do two functions functionToCallWhenOkClicked(parameter)

and confirmBox

at the same time, because you call them immediately with ()

.

However, you can pass a reference to a function like this:

<button ng-click="confirmBox('beSureQuestion', functionToCallWhenOkClicked)">Delete</button>

      

and they call it from the controller when needed:



$scope.confirmBox = function(msg, okCallback) {
    // some checks ...
    okCallback();
}

      

UPD. From @Marcel Ennix's comment. In order to be able to pass additional parameters, it is optimal to pass one more argument to the function confirmBox

:

ng-click="confirmBox('beSureQuestion', functionToCallWhenOkClicked, {para1:value1, para2, value2})"

      

+3


source


Since JavaScript is a functional programming language, there is really no distinction between variables and functions. A variable is just a simple function that returns its value. So to use functions as parameters, just pass the function to the view by adding it to $scope

in your angular controller:

$scope.myCallback = function(anyParameter) {
    //do some stuff
    return "some stuff" + anyParameter;
}

$scope.anyFunction = function(value,callback,parameter) {
    //do something with value
    ...
    //do the callback
    callback(parameter);
}

      



now you can pass this callback function inside your template:

<div ng-click="anyFunction(someValue, myCallback, someParameter)">

      

+1


source







All Articles