我的ng-class出现了一些奇怪的问题,我怀疑这与比赛条件有关。

这是矮人example

这是相关的js代码

    self.slideLeft = function() {
      if (self.end_index < self.list_of_stuff.length) {
          self.direction = 'left';

          debugger;
          self.start_index = self.start_index + 4;
          self.end_index = self.end_index +  4;
          self.display_list = self.list_of_stuff.slice(self.start_index, self.end_index);
      }

    }

    self.slideRight = function() {
      if (self.start_index > 0) {
          self.direction = 'right';
          debugger;

          self.start_index = self.start_index - 4;
          self.end_index = self.end_index -  4;
          self.display_list = self.list_of_stuff.slice(self.start_index, self.end_index);
      }
    }

这是相关的HTML
  <div class="stuff-wrapper">
    <div class="stuff"
         ng-class="bCtrl.directionClass()"
         ng-repeat="stuff in bCtrl.display_list">
      {{stuff}}
    </div>
  </div>

这是动画。
.left.ng-enter,
.left.ng-leave {
    -webkit-transition: all 1s ease-in-out;

}

.left.ng-enter {
    transition-delay: 0.7s;
    opacity: 0;
    left: 10%;
}
.left.ng-enter-active {
    opacity: 1;
    left: 0;
}

.left.ng-leave {
    opacity: 1;
    left: -10%;
}
.left.ng-leave-active {
    left: -20%;
    opacity: 0;
}

这是一个简单的应用程序,可左右滑动数字列表。

如果按下左按钮,数字将向左滑动。

如果按下向右按钮,数字将向右滑动。

但是我们看到,如果方向发生变化,数字将首先沿错误的方向滑动,随后的方向将是正确的。

我怀疑这是由于种族状况造成的。

确实,我看到在使用调试器更改ng-class方向后,并没有立即应用self.direction

这很好奇。

有办法解决这个问题吗?

最佳答案

引用此(https://stackoverflow.com/a/21664152/2402929)问题的答案:



您的元素将在与更新CSS类相同的摘要循环中删除。含义-CSS不会更新,而元素只会被删除。

摘要循环将包含整个ng-click函数,因为使用所有 Angular 内置指令,代码都包装在$ scope。$ apply调用中。

澄清:



您可以在此处(http://jimhoskins.com/2012/12/17/angularjs-and-apply.html)了解更多信息。

因此,解决您的问题的方法是将数组中的数据删除包装到$ timeout块中,这将延迟对一个摘要循环的DOM操作,并将类的更改和数据的删除分开:

self.slideLeft = function() {
          if (self.end_index < self.list_of_stuff.length) {
              self.direction = 'left';

              self.start_index = self.start_index + 4;
              self.end_index = self.end_index +  4;
              $timeout(function(){
                self.display_list = self.list_of_stuff.slice(self.start_index, self.end_index);
              });
          }

        }

        self.slideRight = function() {
          if (self.start_index > 0) {
              self.direction = 'right';

              self.start_index = self.start_index - 4;
              self.end_index = self.end_index -  4;
              $timeout(function(){
                self.display_list = self.list_of_stuff.slice(self.start_index, self.end_index);
              });
            }
        }

这是一个工作的小伙子:
http://plnkr.co/edit/30wJhL?p=preview

09-30 18:58
查看更多