angularjs中的alert()会导致5条消息而不是1条消息

时间:2015-08-13 16:53:21

标签: javascript angularjs

在学习或调试JS时,可能是“老派”使用警报,但有时我拒绝这样做。我正在学习angularjs,很难理解调度,我的意思是angularjs如何执行不同的指令。 作为一个例子,这里是angularjs中的小应用程序,我无法理解为什么在一个警报上有5条消息???

http://plnkr.co/edit/8j7D0J0a6By447whhpa3?p=preview

<!doctype html>
<html>
<head>
    <title></title>

<style>

.red
  {
    color:red;
  }
</style>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.js"></script>
    <script src="script.js"></script>
</head>

<body ng-app="demoApp">
    <div ng-controller="testCntr">
      <span ng-class="{red: setClass()}">Test color</span>
      <div>{{setClass()}}</div>
    </div>


</body>
</html> 

JS

demoApp = angular.module('demoApp',[]);

demoApp.controller('testCntr', function ($scope) {

  $scope.setClass = function () {
    alert('test');
    return true;
  }

});

1 个答案:

答案 0 :(得分:0)

问题是你一遍又一遍地调用这个功能。改变它是事件驱动的,你会很好:

http://plnkr.co/edit/zh0kIs?p=preview

HTML

<body ng-app="demoApp">

  <div ng-controller="testCntr">
    <span ng-class="{'red': changeClassModel}">Test color</span>
    <br><br>
    <button ng-click="setClass()">Hooray Alerts!</button>
  </div>

</body>

JS:

demoApp = angular.module('demoApp',[]);

demoApp.controller('testCntr', function ($scope) {

  $scope.changeClassModel = false;

  $scope.setClass = function () {
    alert('test');
    $scope.changeClassModel = true;
    return true;
  }

});