Oreoluwa
Oreoluwa

Reputation: 519

pass callback param to controller function in angular

say i have a controller like so (irrelevant code removed for brievity)

app.controller('MyCtrl', [function(){
    vm = this

    vm.funcA = function(param){
        alert("Func a called with " + param);
    }

    vm.funcB = function(param, callBack){
        //do stuff
        callBack(param);
    }
}])

and in view like so

<div ng-controller = "MyCtrl as myctrl">
    <button ng-click = "myctrl.funcB('Hello World', myctrl.funcA)"> Click Me</button>
</div>

running this gives an error "callBack is not a function", i know that there are other ways of achieving the result this tries to achieve but how do you pass a function as a parameter to a controller function in angular?

Upvotes: 1

Views: 2061

Answers (1)

Eduardo Reche
Eduardo Reche

Reputation: 31

Just pass the callback params separated to the function

<button ng-click = "myctrl.funcB('Hello World', myctrl.funcA, 'funcA param')"> Click Me</button>

as well in the funcB() signature

vm.funcB = function(param, callBack, param){
    //do stuff
    callBack(param);
}

https://gist.github.com/eduardoreche/6302db667852da0b2485

Upvotes: 1

Related Questions