动态更改ng-click值

时间:2017-06-01 05:04:31

标签: javascript angularjs

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>

这里我想基于使用条件语句的值动态更改ng-click的值,但它没有按预期工作。请帮帮我 提前致谢

2 个答案:

答案 0 :(得分:4)

更改此行,如下所示

因为它已经插值了。您无需再次提及' '来调用范围函数

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

答案 1 :(得分:1)

删除函数中的单引号

更改此

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

到这个

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

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

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

})
&#13;
.test{width:160px;height:30px;background-color:green;color:white}
&#13;
<!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>
&#13;
&#13;
&#13;