Federico Nastasi Federico Nastasi - 11 months ago 53
AngularJS Question

How to make an angular js function to change button content more than one time

html :

<a class="btn btn-lg btn-success" href="#"ng-click="splendido()">{{salute}}</a></p>


var calls=1;

$scope.salute='I'm greeting you for first time';

if(calls==2)$scope.salute="2nd time";
if(calls==3)$scope.salute="3rd time";
if(calls>3)$scope.salute="you're annoying me" ;

the button everytime that is clicked it calls the splendido() function,my goal would be to change the content of the {{salute}} more than one time.
I don't manage to get it right,why it isn't updating as I expected?

I'm using Angular js 1.5.8

Answer Source

First, you need to instantiate the variable 'salute' outside of the function, to get a default value when the controller is loaded.

Second, as in the first step, you need to initialize the 'calls' variable outside of the function, if you don't do this, 'call' always return 1.

This code works!

$scope.salute="I'm greeting you for first time";
var calls=1;
$scope.splendido = function() {
    if(calls==1)$scope.salute="2nd time";
    if(calls==2)$scope.salute="3rd time";
    if(calls>2)$scope.salute="you're annoying me" ;