jQuery slider not working in angularjs

2019-03-22 10:46发布

问题:

My slider wont come up on first time navigation of the page. However when I hard refresh the page then it comes up and also if I replace the <div ng-view></div> code with the front.html page content then also the slider starts working. Let me know what I am doing wrong in angular as I believe it is something basic that I am missing.

Following is my layout code -

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>WEBSITE</title>
<link rel="stylesheet" href="assets/css/style.css" />
<link rel="stylesheet" href="assets/css/flexslider.css" type="text/css" media="screen" />
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/jquery.flexslider.js"></script>
<script src="assets/js/angular.js"></script>
<script src="assets/js/angular-route.js"></script>
<script src="controllers/mainController.js"></script>
<script>
    jQuery(document).ready(function($) {
    jQuery(window).load(function() {
      jQuery('.flexslider').flexslider({
        animation: "slide"
      });
    });
});
</script>
</head>
<body ng-controller="mainController">
    <header ng-include="'includes/header.html'"></header>
    <nav ng-include="'includes/navmenu.html'"></nav>
    <div ng-view></div>
    <footer ng-include="'includes/footer.html'"></footer>
</body>
</html>

Following is my main controller code -

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function($routeProvider){
    $routeProvider
        .when('/', {
            templateUrl: 'views/pages/front.html',
            controller: 'frontCtrl'
        })
});

In front.html I have slider code -

<div class="flexslider">
  <ul class="slides">
    <li>
      <img src="assets/images/banner1.jpg">
    </li>
    <li>
      <img src="assets/images/banner2.jpg">
    </li>
     <li>
      <img src="assets/images/banner3.jpg">
    </li>
    <li>
      <img src="assets/images/banner4.jpg">
    </li>
  </ul>
</div>

EDIT -

If I also write this code in the Firebug console then also slider starts working but not on page load -

jQuery('.flexslider').flexslider();

回答1:

The event handler attached with jQuery(window).load will run when the page is fully loaded. However, ng-view hasn't loaded your view yet, which means <div class="flexslider"> doesn't exist.

Move the initialization into a directive:

myApp.directive('flexslider', function () {

  return {
    link: function (scope, element, attrs) {

      element.flexslider({
        animation: "slide"
      });
    }
  }
});

And use like this:

<div class="flexslider" flexslider>

Demo: http://plnkr.co/edit/aVC9fnRhMkKw3xfpm4No?p=preview