Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call two functions on click in angularjs

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.

like image 220
chandradot99 Avatar asked Dec 09 '15 14:12

chandradot99


2 Answers

Just call the functions separated by ;

<button ng-click="first();second()">click</button>
like image 63
Tarun Dugar Avatar answered Sep 22 '22 00:09

Tarun Dugar


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).

like image 29
Chris Hermut Avatar answered Sep 18 '22 00:09

Chris Hermut