【问题标题】:angularjs - ng-show doesn't update class when $interval triggersangularjs - ng-show 在 $interval 触发时不更新类
【发布时间】:2015-02-03 11:53:11
【问题描述】:

尝试使用 Angular 中的 $interval 来使用 ng-show 更改列表中当前可见的项目。检查 html,我注意到 ng-show 的角度从真/假发生了变化,但它并没有删除 ng-hide 类。 html很简单:

<h1>Hello Plunker!</h1>
<div ng-controller="MyCtrl">
  <div>Iterator: {{i}}</div>
  <ul>
    <li ng-repeat="d in data" ng-show="{{i == $index}}">{{i}} - {{$index}} - {{d}}</li>
  </ul>
</div>

app.js 也很基础:

(function(){  
   var app = angular.module('MyApp', ['my-controller']);
})();

和我的模块/控制器

(function(){
  var app = angular.module('my-controller', []);

  app.controller('MyCtrl', ['$scope', '$interval', function($scope, $interval){
    $scope.data = [111, 222, 333, 444];
    $scope.i = 0;
    var timeoutId;


    timeoutId = $interval(function(){
      $scope.i ++;  
      if ($scope.i >= $scope.data.length)
        $scope.i = 0;
    },
    1000);


  }]);
})();

Here's my plnkr

【问题讨论】:

    标签: javascript angularjs angularjs-scope angularjs-ng-repeat


    【解决方案1】:

    那是因为您在 ng-show 表达式中使用插值 ({{i == $index}}) 设置字符串“true”/“false”,而不是直接提供表达式。

    ng-show="i == $index"
    

    Plnkr

    只是补充说明,看看ng-show source code

     scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
        // we're adding a temporary, animation-specific class for ng-hide since this way
        // we can control when the element is actually displayed on screen without having
        // to have a global/greedy CSS selector that breaks when other animations are run.
        // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
        $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
          tempClasses: NG_HIDE_IN_PROGRESS_CLASS
        });
      });
    

    它在属性值上注册一个监视,因此当使用插值(首先呈现)时,它实际上为第一项设置监视"true",为最后三个设置监视"false"(如预期的那样)。一切都很好,手表第一次运行进行脏检查,它被解析为布尔值,并将 ng-hide 类添加到最后 3 个,第一个仍然显示。所以到目前为止,watch 设置在范围上的字符串“true/false”上,它永远不会改变并且 watch 不再执行(因为它总是会在您的情况下由超时触发的摘要周期返回相同的值)和项目显示仍然显示,隐藏仍然隐藏,因为它永远没有机会执行add/removeClass。现在,当您使用表达式时,它将在每次摘要发生时进行评估,布尔标志评估为表达式的值发生变化,观察者被执行,类被按预期添加/删除。

    【讨论】:

      猜你喜欢
      • 2016-02-27
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      相关资源
      最近更新 更多