How to call two functions on click in angularjs
Asked Answered
B

2

5

I have two functions inside my controller

$scope.first = function()
{
    console.log("first");
}

$scope.second = function()
{
console.log("hello");
}

Now in my template i give call to first function

<button ng-click="first()">click</button>

Now I want that as soon as my first function complete its execution, automatically my second function starts executing without any click.

That is on single click first function executes and then second function executes respectively.

Brigidbrigida answered 9/12, 2015 at 14:12 Comment(0)
O
5

Or you can do:

function first() {
    // Do stuff
}

function second() {
   // Do stuff
}

$scope.runBoth = function () {
    first();
    second();
}

The good thing with that approach is that you can listen to first() return and based on that run/skip execution of second() etc.

Also by keeping first() and second() as just javascript functions you are not adding unnecessary watchers (assuming that you're not using first() and second() somewhere else).

Odelia answered 9/12, 2015 at 14:21 Comment(2)
of corse this will run ok, but it's easier to call both function in the ng-clickOld
It all depends on a use case.Odelia
T
10

Just call the functions separated by ;

<button ng-click="first();second()">click</button>
Tollbooth answered 9/12, 2015 at 14:12 Comment(0)
O
5

Or you can do:

function first() {
    // Do stuff
}

function second() {
   // Do stuff
}

$scope.runBoth = function () {
    first();
    second();
}

The good thing with that approach is that you can listen to first() return and based on that run/skip execution of second() etc.

Also by keeping first() and second() as just javascript functions you are not adding unnecessary watchers (assuming that you're not using first() and second() somewhere else).

Odelia answered 9/12, 2015 at 14:21 Comment(2)
of corse this will run ok, but it's easier to call both function in the ng-clickOld
It all depends on a use case.Odelia

© 2022 - 2024 — McMap. All rights reserved.