为什么这个ng-change不会触发

时间:2014-11-09 23:17:12

标签: angularjs

我添加了一个下拉列表并将selectChange()方法连接到AngularJS站点上常见的基本ng-change演示。问题是当下拉列表被更改时,selectChange()不会触发。谁能告诉我为什么? Plunkr here

<body ng-app="changeExample">
    <script>
    angular.module('changeExample', [])
      .controller('ExampleController', ['$scope', function($scope) {
        $scope.counter = 0;
        $scope.change = function() {
          $scope.counter++;
        };

        $scope.selectChange = function(){
          alert('foo');
          $scope.counter++;
        };

      }]);
  </script>
  <div ng-controller="ExampleController">
    <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
    <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
    <label for="ng-change-example2">Confirmed</label><br />

    <tt>debug = {{confirmed}}</tt><br/>
    <tt>counter = {{counter}}</tt><br/>

    <select id='drpCars' ng-change="selectChange()">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="opel">Opel</option>
      <option value="audi">Audi</option>
    </select>

    <input type="text" name="CarValue"><br>
  </div>

2 个答案:

答案 0 :(得分:1)

您需要应用ng-model的{​​{1}}属性来触发


来自文档

  

仅当输入值的更改导致将新值提交给模型时,才会评估ngChange表达式。

https://docs.angularjs.org/api/ng/directive/ngChange

答案 1 :(得分:0)

尝试使用此修改后的代码。

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example - example-ngChange-directive-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>



</head>

<body ng-app="changeExample">
    <script>
    angular.module('changeExample', [])
      .controller('ExampleController', ['$scope', function($scope) {
        $scope.counter = 0;
        $scope.change = function() {
          $scope.counter++;
        };

        $scope.selectChange = function(value){
          alert(value);
          $scope.counter++;
        };

      }]);
  </script>
  <div ng-controller="ExampleController">
    <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
    <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
    <label for="ng-change-example2">Confirmed</label><br />

    <tt>debug = {{confirmed}}</tt><br/>
    <tt>counter = {{counter}}</tt><br/>

    <select id='drpCars' ng-model = "value" ng-change="selectChange(value)">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="opel">Opel</option>
      <option value="audi">Audi</option>
    </select>

    <input type="text" name="CarValue"><br>
  </div>

</html>