2016-09-25 96 views
0

我想從Materialize框架中使用angularjs中的路由運行函數.parallax()。我已經爲每個模板配置了命令document.ready,但這不起作用。這只是第一次。測試(); document.ready調用函數的最佳方法是什麼?使用路線?我將等待!謝謝!用angularjs路徑運行document.ready

我的路線的HTML模板:

<!-- JS --> 
<script type="text/javascript"> 
    $(document).ready(function(){ 
     $('.parallax').parallax(); //Run just in the first time 
    }; 
</script> 

<!-- Template --> 
<div class="" ng-controller="homeCtrl"> 
... 
</div> 

控制器:

app.controller('homeCtrl', ['$scope', function($scope){ 

    //Ready 
    angular.element(document).ready(function() { 
     $('.parallax').parallax(); // Doesn't work 
    }); 

}]); 

謝謝!

+0

我使用Materialise的CSS採取從控制器參數的指令

<div class="parallex" run-function-again="runFunctionAgain" test-plugin><div> 

在控制器中。我忘了說 –

+0

你不......你把代碼放在指令中,所以代碼只在元素存在後才運行。 DOM代碼不屬於控制器 – charlietfl

回答

0

顯然,控制器中的代碼不會工作,因爲這是一個單頁面應用程序,並且在加載控制器時,文檔已經加載並且調用腳本標記中的回調。我想你可以創建一個像

App.directive('testJquery', function() { 
return { 
    restrict: 'A', 
    link: function(scope, element, attrs) { 
     $(element).parallex(); 
    } 
    }; 
}); 

和HTML一個指令是這樣,假設你parallex類元素存在於路線的每個視圖

<div class="parallex" test-plugin><div> 

如果有一個DIV它超出了NG-視圖,並且希望每次改變路線,那麼你可以在你的主控制器要做什麼時間(在此元素是存在的)

更改指令

調用元素的parallex或任何testFuntion
App.directive('testJquery', function() { 
return { 
    restrict: 'A', 
    scope:{ 
     runFunctionAgain:'=' 
    }, 
    link: function(scope, element, attrs) { 
     $(element).parallex(); 
     scope.$watch('runFunctionAgain', function(){ 
      if(scope.runFunctionAgain){ 
       $(element).parallex(); 
       scope.runFunctionAgain = false; 
      } 
     }) 
    } 
    }; 
}); 

而且

scope.runFunctionAgain = true; 
$scope.$on('$routeChangeStart', function (event, next, current) { 
    scope.runFunctionAgain = true; 
});