【问题标题】:Run javascript code after all the AngularJS template directives have loaded在加载完所有 AngularJS 模板指令后运行 javascript 代码
【发布时间】:2017-08-16 11:23:41
【问题描述】:

我有一个使用 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"
    };
});

有一个名为 loginController 的控制器在使用 ngRoutes 的路由中指定,如下所示:

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 等到模板加载完毕,然后滚动到它的最佳方法是什么?

这可以通过使用promises来实现吗,我以前从未使用过它们?

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    如果您想使用 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 秒。您可以根据需要更改时间。

    【讨论】:

    • 谢谢,您的超时解决方案有效,但它不能防错。我将调查这些承诺并尝试像那样实施它
    【解决方案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'));
                }
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 2014-04-25
      • 2014-03-08
      • 1970-01-01
      相关资源
      最近更新 更多