简体   繁体   English

Angular-如何在ng-view中调用javascript函数

[英]Angular - how to call javascript function inside ng-view

I am building a single page app with Angular JS. 我正在使用Angular JS构建单页应用程序。 Here are my files 这是我的档案

index.html 的index.html

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

dishestemplate.html dishestemplate.html

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

bxslider.js has some function and bxslider.js具有一些功能,并且

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

dishesapp.js 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. index.html成功加载了所有局部视图。 But template.html cannot load the javascript file so the slider doesnt work. 但是template.html无法加载javascript文件,因此滑块不起作用。 Is there a way to solve this problem? 有办法解决这个问题吗?

$(document).ready(function (){}) shouldn't be used in conjunction with Angular. $(document).ready(function (){})不应与Angular结合使用。

What you need is a directive . 您需要的是一个指令 Create a directive for you slider and use on your dishestemplate.html file. 为您的滑块创建一个指令,并在您的dishstemplate.html文件中使用。 In the directive you call your jQuery plugin. 在指令中,您调用jQuery插件。

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 src="js/bxslider.js"></script>移至index.html,并将以下脚本添加到dishtemplate.html的末尾/底部

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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