ngView Animation Enter在加载第一页时未启动



几天来,我一直在与网站上的一个非常微妙的错误作斗争,但找不到任何解决方案(也许我对AngularJs的了解还不够)

我使用的是最新的angular(v1.6.1)、ngRoute和ngAnimate。

问题是,当你去网站时(当网站第一次加载时),ngView动画输入不会启动。

这是我的代码:

var app = angular.module('app', ['ngAnimate', 'ngRoute']);
app.animation('.view', function () {
return {
enter : function (element, done) {
alert('enter');
done();
},
leave : function (element, done) {
alert('leave');
done();
}
}
});
//Config
app.config(function ($routeProvider, $locationProvider, $httpProvider){
$routeProvider.when('/test.php',{
template : function () {
return "<div>Welcome to test page</div>";
}
});
$routeProvider.when('/test.php/:path',{
template : function () {
return "<div>Inside page</div>";
}
});
$locationProvider.html5Mode({enabled: true, requireBase: true});
});

我在GitHub上看到过这个问题:https://github.com/angular/angular.js/issues/10536

也就是说"这是一个特性,而不是一个bug"。但问题是,在制作网站上,它有时会启动,有时不会(尤其是在safari和移动浏览器中)。

例如,当我使模板加载速度变慢时:

$routeProvider.when('/test.php',{
template : function () {
return "<div>Welcome to test page</div>";
},
resolve: {
message: function ($timeout, $q) {
console.log('asdasa')
return $q(function(resolve){
$timeout(function () {
resolve('message');
},1000);
});
}
}
});
$routeProvider.when('/test.php/:path',{
template : function () {
return "<div>Inside page</div>";
},
resolve: {
message: function ($timeout, $q) {
return $q(function(resolve){
$timeout(function () {
resolve('message');
},1000);
});
}
}
});

或者使用PHP:

sleep(1)

enter事件会触发,但当它在缓存中或浏览器快速获取时,可能不会触发。

github上有一些技巧,但我不太喜欢快速技巧,因为它们很可靠。

例如,github上提到的这个肮脏的黑客不再工作:

$rootElement.data("$$ngAnimateState").running = false;

我也试过:

app.run(function($animate) {
$animate.enabled(true);
});

但它有一种非常奇怪的行为,在狩猎中也无济于事。

这是一个JSBIN示例

提前谢谢,我会等你的帮助!

因此,经过几天对github的讨论,我们找到了一个解决方案:

首先,我们必须在app.run上启用动画(默认情况下已禁用)。然后根据我们的情况,我们应该禁用身体上的动画,并直接在视图上启用它。但是,只要我们不能在[ng-view]元素上启用动画,因为我们不能在$animate之前获得新创建的节点,我们就应该将[ng-view]element包装在容器div中。

HTML:

<div id="view-container">
<div class="view" ng-view></div>
</div>

JS:

app.run(function($animate) {
$animate.enabled(true);
$animate.enabled(document.body, false);
$animate.enabled(document.getElementById('view-container'), true);
});

但这还不够,因为angular检查文档。虽然这是真的,但$animation不起作用。因此,我们必须覆盖角度函数,以便$animation始终有效(尽管这可能对动画平滑度有点危险):

app.value('$$isDocumentHidden', function() { return false; });

就是这样!希望有人会发现它有用!

最新更新