suchen

Heim  >  Fragen und Antworten  >  Hauptteil

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<code><section ng-app="app" ng-controller="ctrl">

  <p ng-show="check && form.$invalid"></p>

  <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;

  }

})</code>

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

phpcn_u1582phpcn_u15822877 Tage vor662

Antworte allen(2)Ich werde antworten

  • 我想大声告诉你

    我想大声告诉你2017-05-15 17:05:45

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    <code class="html"><p 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 }}

    </p></code>

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    <code class="javascript">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

        }];

    });</code>

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

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

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

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

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

    文档地址: ngRepeat

    Antwort
    0
  • PHP中文网

    PHP中文网2017-05-15 17:05:45

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

    Antwort
    0
  • StornierenAntwort