如何在加载AngularJS部分模板后应用jquery

VAA*_*AAA 19 jquery angularjs angular-routing

我有一个简单的网站,它实现了jQuery,以便在Index.html顶部横幅中创建一些带有一些图像的Slider.

现在,我想使用AngularJS,所以我将HTML代码分解为单独的部分.

  1. 页脚
  2. 顶级横幅

如果我在原始版本中运行Index.html(不应用AngularJS模式),那么我可以看到滑块工作正常.

在应用AngularJS模式时,我将顶部横幅HTML移动到部分html,然后将ng-view应用于顶部横幅最初所在的div.

var app = angular.module('website', ['ngRoute']);
app.config(function($routeProvider) {
    $routeProvider.
    when('/about',{templateUrl:'app/partials/about.html'}).
    when('/contact',{templateUrl:'app/partials/contact.html'}).
    otherwise({redirectTo:'/home',templateUrl:'app/partials/home.html'})
});
Run Code Online (Sandbox Code Playgroud)

当我刷新页面滑块不工作时,渲染为简单的html没有任何jQuery效果,真是一团糟.

这个部分有一些jQuery插件,通常由document.ready激活.但是当角度载荷部分在ng视图中时,此事件不会触发.如何调用此事件来初始化jQuery插件?

有任何线索如何解决这个问题?

感谢任何帮助.

Aar*_*ron 20

指定路线时,您还可以指定控制器,因此您的路线将如下所示:

var app = angular.module('website', ['ngRoute']);
app.config(function($routeProvider) {
    $routeProvider.
        when('/about',{templateUrl:'app/partials/about.html', controller: 'aboutCtrl'}).
        when('/contact',{templateUrl:'app/partials/contact.html', controller: 'contactCtrl'}).
        otherwise({redirectTo:'/home',templateUrl:'app/partials/home.html', controller: 'homeCtrl'})
    });
Run Code Online (Sandbox Code Playgroud)

现在,您可以在每个控制器内部定义您想要执行的操作,jquery-wise,作为函数的一部分,如下所示:

angular.module('website').controller('aboutCtrl', ['$scope', function ($scope) {

   $scope.load = function() {
       // do your $() stuff here
   };

   //don't forget to call the load function
   $scope.load();
}]);
Run Code Online (Sandbox Code Playgroud)

合理?

  • 这对我不起作用.$()找不到元素.它们尚未加载 (3认同)

Sea*_*son 10

其他提供的答案将起作用,但它们绑定到控制器,因此不具有可扩展性和可重用性.

要在评论中提到真正的"Angular"方式,您应该使用指令.这样做的好处是,您可以使用相同的代码创建多个实例,并可以将属性传递给指令逻辑以"自定义"该指令.这是我使用bxSlider插件使用它的一种方式的示例:

JS:

app.directive('slider',  ['$rootScope', function($rootScope) {
return {
    restrict: 'EA',
    templateUrl: '/path/to/template',
    link: function(scope, iElement, attrs) {
        //attrs references any attributes on the directive element in html

        //iElement is the actual DOM element of the directive,
        //so you can bind to it with jQuery
        $(iElement).bxSlider({
            mode: 'fade',
            captions: true
        });

        //OR you could use that to find the element inside that needs the plugin
        $(iElement).find('.bx-wrapper').bxSlider({
            mode: 'fade',
            captions: true
        });

       }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

HTML:

<div slider some-attibute="some-attribute"></div>
Run Code Online (Sandbox Code Playgroud)

在指令模板中,您可以使用滑块包装器和幻灯片,您可以使用绑定到范围数据的ng-repeat动态构建.

我建议阅读Dan Wahlin关于创建自定义指令以及如何充分利用它们的强大功能的优秀文章.