運行

2017-08-16 57 views
0

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

而且,我的登錄-card.html看起來是這樣的:

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

的問題是,諧音前的$的document.ready功能火災被加載,所以它無法找到名爲page-top的指定類的div。

什麼是最好的方式讓Angular等到模板被加載,所以它可以滾動到它?

這可以通過使用承諾來實現,我從來沒有使用過它們嗎?

回答

0

如果你想使用的承諾,然後看到這個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秒的延遲。您可以根據您的要求更改時間。

+0

感謝,與超時工作的解決方案可用,但它不是防止出錯。我會調查承諾,並嘗試像這樣實施 – user3362334

0

我覺得寫指令中的鏈接功能時,您的代碼將做到這一點,因爲在鏈接方法登錄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')); 
      } 
     } 
    });