簡體   English   中英

加載所有AngularJS模板指令后運行javascript代碼

[英]Run javascript code after all the AngularJS template directives have loaded

我有一個使用AngularJS模板指令的html頁面,如下所示:

<div class="row">
        <div class="col-sm-12">
            <div logo></div>
            <div login-card></div>
            <div info></div>
        </div>
    </div>

我的指令如下所示:

myApp.directive('logo', function(){
    // Runs during compile
    return {
        templateUrl: "components/logo.html"
    };
});

myApp.directive('loginCard', function(){
    // Runs during compile
    return {
        templateUrl: "components/login-card.html"
    };
});

myApp.directive('info', function(){
    // Runs during compile
    return {
        templateUrl: "components/info.html"
    };
});

在路由中使用ngRoutes指定了一個名為loginController的控制器,如下所示:

when("/login", {
        templateUrl: 'login/login.html?version=3',
        controller: 'loginController'
    }).

頁面加載完成后,我希望頁面直接滾動到較小設備上的登錄卡。 為此,我將這段代碼放在我的loginController中:

$document.ready( function () {
        if ( $(window).width() < 768 ) {
            $('html,body').animate({ scrollTop: $(".page-top").offset().top}, 'slow');
        }
    })

而且,我的login-card.html看起來像這樣:

<div class="page-top">
 --some code here--
</div

問題在於$ document.ready函數在加載局部函數之前啟動,因此無法找到具有指定類page-top的div。

什么是使Angular等到模板加載后才能滾動到的最佳方法?

可以通過使用我以前從未使用過的諾言來實現嗎?

如果您要使用promise,請參閱此http://jsfiddle.net/Zenuka/pHEf9/21/但我認為另一種解決方案是可以使用$timeout解決此問題

$timeout( function(){
            $document.ready( function () {
        if ( $(window).width() < 768 ) {
            $('html,body').animate({ scrollTop: $(".page-top").offset().top}, 'slow');
        }
    })
        }, 2000 );

現在,您的函數將延遲2秒。 您可以根據需要更改時間。

我認為在指令的鏈接函數中編寫代碼將做到這一點,因為在鏈接方法上,登錄html在DOM中可用

myApp.directive('loginCard', function () {
        return {
            templateUrl: "login-card.html",
            link: function (scope, element, attrs) {
                //Your code to adjust view
                console.log(document.getElementsByClassName('page-top'));
            }
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM