Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript $animate.removeClass在没有$evalAsync inside指令的情况下无法工作?_Javascript_Angularjs_Angularjs Directive_Ng Animate - Fatal编程技术网

Javascript $animate.removeClass在没有$evalAsync inside指令的情况下无法工作?

Javascript $animate.removeClass在没有$evalAsync inside指令的情况下无法工作?,javascript,angularjs,angularjs-directive,ng-animate,Javascript,Angularjs,Angularjs Directive,Ng Animate,我已经创建了一个指令,可以在模型更改的视图中淡出和淡出 app.controller('myCtrl', function($scope, $interval) { $scope.number = 0; $interval(function() { $scope.number++; }, 1000); }); app.directive('fadeOnChange', function($timeout, $animate) { return { restric

我已经创建了一个指令,可以在模型更改的视图中淡出和淡出

app.controller('myCtrl', function($scope, $interval) {
  $scope.number = 0;
  $interval(function() {
    $scope.number++;
  }, 1000);
});

app.directive('fadeOnChange', function($timeout, $animate) {
  return {
    restrict: 'E',

    //We output the value which will be set between fades
    template: '{{theFadedValue.nv}}',

    link: function(scope, elem, attr) {
      //The scope variable we will watch
      var vtw = attr.valueToWatch;

      //We add the anim class to set transitions
      $animate.addClass(elem, 'anim');

      //We watch the value 
      scope.$watch(vtw, function(nv) {

        //we fade out
        var promise = $animate.addClass(elem, 'fade-it-out');

        //when fade out is done, we set the new value
        promise.then(function() {

          scope.$evalAsync(function() {
             scope.theFadedValue = {"nv": nv};
            //we fade it back in
            $animate.removeClass(elem, 'fade-it-out');
          });
        });
      })
    }
  };
});
这里是风景

<div ng-controller="myCtrl">
  <h1><fade-on-change value-to-watch="number"></fade-on-change></h1>
</div>

它工作得非常完美,但我想了解为什么我需要使用$apply、$digest、$timeout或$evalAsync来包装对$animate.removeClass的调用,以便它工作?如果我不这样做,这门课就不会被取消(这让我今天下午很头疼)

我对这四种方法很感兴趣,也了解它们的不同之处,但在这种情况下使用其中一种方法的必要性让我感到困惑


基本上异步方法是不直接运行$digest cycle的。(对于
$http
来说是例外情况,因为它内部包装在
$scope.$apply()

在您的情况下,您正在等待异步的完整承诺。这就是为什么您可以使用
$timeout(function(){})
$evalAsync
,在
$scope.$apply()
&
$scope.$apply()
内部运行摘要循环,并更新所有范围变量

$evalAsync在DOM被Angular操作后运行,但是 在浏览器渲染之前

有关何时使用
$scope.$apply()

希望这能消除你的疑虑。谢谢