0

我正在尝试使用 angularjs 中的路由从 Materialize 框架运行函数 .parallax() 。我已经为每个模板配置了命令 document.ready 但这不起作用。这只是第一次。使 document.ready 调用 $('.test').test(); 这样的函数的最佳方法是什么?使用路线?我将等待!谢谢!

我的路线的模板 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
    });

}]);

谢谢!

4

1 回答 1

0

显然,控制器中的代码将不起作用,因为这是一个单页应用程序,并且在加载控制器时,文档已经加载,并且调用了脚本标签中的回调。我认为您可以创建一个指令,例如

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

和 html 一样,假设您的平行类元素存在于路线的每个视图中

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

如果有一个 div 在 ng-view 之外,并且您想在每次更改路由时调用元素上的 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;
           }
       })
    }
  };
});

并从指令中的控制器获取参数

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

在控制器中

   scope.runFunctionAgain = true;
 $scope.$on('$routeChangeStart', function (event, next, current) {
    scope.runFunctionAgain = true;
 });
于 2016-09-25T18:01:35.213 回答