javascriptangularjsurl-routingng-view

Angular - how to call javascript function inside ng-view


I am building a single page app with Angular JS. Here are my files

index.html

<script src="js/dishesapp.js"></script>
<div ng-view></div>

dishestemplate.html

<script src="js/bxslider.js"></script>  (which is for my image slider)

bxslider.js has some function and

$(document).ready(function ()
{
    $('.bxslider').bxSlider();
});

dishesapp.js

var dishesApp = angular.module('dishesApp', ['ngRoute']);
        dishesApp.config(function ($routeProvider) {
            $routeProvider
                    .when('/', {templateUrl: 'partials/default.html'})
                    .when('/Noodles', {templateUrl: 'partials/dishtemplate.html', controller: 'NoodlesCtrl'})
                    .when('/Rolls', {templateUrl: 'partials/dishtemplate.html', controller: 'RollsCtrl'})
                    .when('/Pancakes', {templateUrl: 'partials/dishtemplate.html', controller: 'PancakesCtrl'})
                    .when('/Rice', {templateUrl: 'partials/dishtemplate.html', controller: 'RiceCtrl'})
                    .when('/FamilyStyle', {templateUrl: 'partials/dishtemplate.html', controller: 'FamilyStyleCtrl'})
                    .when('/Others', {templateUrl: 'partials/dishtemplate.html', controller: 'OthersCtrl'})
                    .otherwise({redirectTo: '/'});
    });

The index.html successfully load all the partial views. But template.html cannot load the javascript file so the slider doesnt work. Is there a way to solve this problem?


Solution

  • $(document).ready(function (){}) shouldn't be used in conjunction with Angular.

    What you need is a directive. Create a directive for you slider and use on your dishestemplate.html file. In the directive you call your jQuery plugin.

    In dishestemplate.html

    <div my-slider></div>
    

    Your directive

    angular.module('yourAngularApp', [])
        .directive('mySlider', function() {
          return {
              restrict: 'A',
              template: '<div class="slider">The HTML for your slider</div>',
              link: function (scope, element, attrs) {
                  element.bxSlider(); //call your plugin here!
              }
          };
    });