I am trying to run the function .parallax() from Materialize framework using routes in the angularjs. I already config the command document.ready for each template but this doesn't work. This works just in the first time. What is the best way to make document.ready calling functions like $('.test').test(); using routes? I will wait! Thanks!
Template HTML of my route:
<!-- JS -->
<script type="text/javascript">
$(document).ready(function(){
$('.parallax').parallax(); //Run just in the first time
};
</script>
<!-- Template -->
<div class="" ng-controller="homeCtrl">
...
</div>
Controller:
app.controller('homeCtrl', ['$scope', function($scope){
//Ready
angular.element(document).ready(function() {
$('.parallax').parallax(); // Doesn't work
});
}]);
Thanks!
Obviously the code in controller will not work as this is a single page application and by the time the controller is loaded the document is already loaded and the call back in the script tag is called. I think you can create a directive like
App.directive('testJquery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$(element).parallex();
}
};
});
and the html be like, assuming your parallex class elements are present in each view of the routes
<div class="parallex" test-plugin><div>
If there is one div which is outside the ng-view and you want to call the parallex or any testFuntion on the element every time you change route then what you can do in your main controller(under which this element is there)
Change the directive to
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;
}
})
}
};
});
And take the parameter from the controller in the directive
<div class="parallex" run-function-again="runFunctionAgain" test-plugin><div>
In the controller
scope.runFunctionAgain = true;
$scope.$on('$routeChangeStart', function (event, next, current) {
scope.runFunctionAgain = true;
});