![](/img/trans.png)
[英]AngularJS: How to place enter animation for each element on ngView
[英]ngView Animation Enter not firing on first page load
幾天來,我一直在努力解決自己網站上的一個非常細小的錯誤,但找不到任何解決方案(也許我對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
那就是“這是一個功能,而不是一個錯誤”。 但問題是,在生產網站上,它有時會觸發,有時卻不會觸發(尤其是在野生動物園和移動瀏覽器中)。
例如,當我使模板加載速度變慢時:
$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)
輸入事件會觸發,但是也許當它在緩存中或瀏覽器快速獲取它時,它不會。
github上有一些駭客,但是由於它們的可靠性,我不是快速駭客的忠實擁護者。
例如,在github上提到的這個骯臟的hack不再起作用:
$rootElement.data("$$ngAnimateState").running = false;
我也嘗試過:
app.run(function($animate) {
$animate.enabled(true);
});
但是它有一個非常奇怪的行為,在野生動物園中沒有幫助。
這是一個JSBIN示例
在此先感謝您,我將等待您的幫助!
因此,在github上討論了幾天之后,我們找到了一個解決方案:
首先,我們必須在app.run上啟用動畫(默認情況下已禁用)。 然后,根據情況,我們應該在主體上禁用動畫,然后直接在視圖上啟用它。 但是,只要我們不能在[ng-view]元素上啟用動畫,因為我們無法在$ animate之前掌握新創建的節點,則應將[ng-view]元素包裝在容器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);
});
但是,這還遠遠不夠,因為角度檢查document.hidden,雖然正確,但$ animation無效。 因此,我們必須重寫角度函數,以使$ animation始終有效(盡管這對於動畫的平滑性可能有些危險):
app.value('$$isDocumentHidden', function() { return false; });
而已! 希望有人會發現它有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.