简体   繁体   中英

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?

$(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!
          }
      };
});

Move <script src="js/bxslider.js"></script> to index.html and add the following script at the end/bottom of your dishtemplate.html

<script>
    $('.bxslider').bxSlider();
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM