Abhishek
Abhishek

Reputation: 351

Change ng-click value dynamically

var app=angular.module('ang',[]);
app.controller('ctr',function($scope){

$scope.run=function(){alert("run")}
$scope.break=function(){alert("break")}

})
.test{width:160px;height:30px;background-color:green;color:white}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <body>

    <div ng-app="ang" ng-controller='ctr'>
 
      <button class="test" ng-click="a?'run()':'break()'">click=calling...{{a?'run()':'break()'}}</button>
    <button ng-click="a=!a">click me</button>{{a}}

    </div>

  </body>
</html>

Here i want to dynamically change the value of ng-click based on a value using conditional statement,but it is not working as expected.Please help me out Thanks in advance

Upvotes: 1

Views: 813

Answers (2)

Ram_T
Ram_T

Reputation: 8484

Change this line shown as below

Because it is already interpolated. You need not to mention ' ' again to call the scope function

<button class="test" ng-click="a?run():break()">click=calling...{{a?'run()':'break()'}}</button>

Upvotes: 4

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41445

remove the single quote in the function

change this

{{a?'run()':'break()'}}

to this

{{a?run():break()}}

var app=angular.module('ang',[]);
app.controller('ctr',function($scope){

$scope.run=function(){alert("run")}
$scope.break=function(){alert("break")}

})
.test{width:160px;height:30px;background-color:green;color:white}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <body>

    <div ng-app="ang" ng-controller='ctr'>
 
      <div class="test" ng-click="a?'run()':'break()'">click=calling....{{a?run():break()}}</div>
    <button ng-click="a=!a">click me</button>{{a}}

    </div>

  </body>
</html>

Upvotes: 1

Related Questions