首页 > 请问ng-click="alterCheck()"和ng-click="check=true"有什么不同?

请问ng-click="alterCheck()"和ng-click="check=true"有什么不同?

<section ng-app="app" ng-controller="ctrl">
  <div ng-show="check && form.$invalid"></div>
  <form name="form" ng-submit="init()">
    <input type="text" ng-model="text" required/>
    <!--     <input type="submit" ng-click="alterCheck()"/> -->
    <input type="submit" ng-click="check=true"/>
  </form>
</section>
angular.module('app', [])
.controller('ctrl', function($scope){
  $scope.check = false;
  $scope.init2 = function() {
    $scope.text = '';
  }
  $scope.init = function() {
    $scope.init2();
    $scope.check = false;
  }
  $scope.alterCheck = function() {
    $scope.check = true;
  }
})

在实际项目中,使用 ng-click="check=true" 的方法会造成点击后 div 处于显示的状态,而 ng-click="alterCheck()" 则不会,请问这是什么原因呢?
上述代码无法复现我所说的现象。有什么额外的原因可能造成这一现象吗?


值的复制和对象的引用的区别,这个问题不好回答啊,重现不了错误,只能大概觉得。


我在这个例子里可以重现类似你描述的问题(因为之前遇到过,所以多看了几眼):

<div ng-controller="DemoCtrl">
  <ul>
    <li ng-repeat="item in items">
      <input type="radio" name="group" ng-model="item.checked" ng-click="checkIndex = $index">{{ item.name }}
      <!-- <input type="radio" name="group" ng-model="item.checked" ng-click="changeCheckIndex($index)">{{ item.name }} -->
    </li>
  </ul>
  
  checkIndex: {{ checkIndex }}
</div>
var demo = angular.module('myApp', []);

demo.controller('DemoCtrl', function($scope, $timeout){
    $scope.checkIndex = 0;
    
    $scope.changeCheckIndex = function(index){
        $scope.checkIndex = index;
    };
    
    $scope.items = [{
        name: 'Beijing',
        checked: false
    },{
        name: 'Shanghai',
        checked: false
    },{
        name: 'Taiyuan',
        checked: false
    }];
});

这是一个很简单的demo,通过ng-repeat显示一组单选框,通过点击点选按钮,在下面的checkIndex: {{ checkIndex }}中显示选中的单选框的$index。在线demo看这里:jsfiddle

如果运行当前的代码,会发现,{{ checkIndex }}压根没有变化,无论你怎么使劲点,戳破鼠标也没用

但如果template换成我注释掉的那部分代码,改用changeCheckIndex方法,{{ checkIndex }}就变化了。

那么问题来了,如何造成这个局面的?我们还是要回到文档去(最近发现ng的文档还是不错的):

我认为原因在于checkIndex = $index的写法,使得checkIndex是一个在每个template instance中独立$scope下的变量,并不是我们在Controller里定义的那个。

文档地址: ngRepeat

【热门文章】
【热门文章】