1

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?

2
  • 3
    If that's your actual view code, you'll get an error due to the quotes ending the expression too soon. Commented Aug 4, 2015 at 19:54
  • 1
    Works fine... plnkr.co/edit/rUJPGQtAtetrQVPQiNIK?p=preview Commented Aug 5, 2015 at 0:11

1 Answer 1

1

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

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

Comments

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.