【问题标题】:Dynamically loading html into AngularJs with jQuery使用 jQuery 将 html 动态加载到 AngularJs 中
【发布时间】:2015-06-02 10:13:12
【问题描述】:

我在获取 jQuery 时遇到了一些问题,我更熟悉使用 ajax 加载 html 然后将其添加到视图中。模板已经加载,然后我需要通过 ajax 从外部获取一些数据并将其放入元素中。但是 AngularJs 在这一切之前运行,我希望它等到所有数据都加载完毕。

编辑:澄清一下,这里是代码,我运行 custom.js。

 $stateProvider


    // Companyresults
    .state('companyresults', {
        url: "/companyresults.html",
        templateUrl: "views/companyresults.html",            
        data: {pageTitle: 'Dashboard', pageSubTitle: 'statistics & reports'},
        controller: "CompanyResultsController",
        resolve: {
            deps: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load({
                    name: 'MetronicApp',
                    insertBefore: '#ng_load_plugins_before', // load the above css files before '#ng_load_plugins_before'
                    files: [
                            '../../../assets/admin/layout3/scripts/custom.js',
                        'js/controllers/CompanyResultsController.js'
                    ] 
                });
            }]
        }
    });

还有..

     'use strict';

    MetronicApp.controller('CompanyResultsController', function($rootScope, $scope, $http, $timeout) {
        $scope.$on('$viewContentLoaded', function() {   
       // initialize core components
       Metronic.initAjax();
   });
 });

【问题讨论】:

标签: jquery html ajax angularjs


【解决方案1】:

您可以制作自定义指令并在链接函数中调用您的 jquery 插件

  var directiveModule = angular.module("directiveModule", []);

    directiveModule.directive('wrapJqueryplugin', function() {
        return {
            restrict : 'E',
            link : function(scope, element, attrs) {        
    *********your jquery code ****************
});

在你看来

    <wrap-jqueryplugin>
***    any Dom Elements ***
    </wrap-jqueryplugin>

【讨论】:

    【解决方案2】:

    不要使用ng-app 指令来启动应用程序,而是应该在您认为文档准备就绪时运行angular.bootstrap(document, ['app']);(例如在jQuery 回调中);

    请注意,您也可以在 Angular 中使用 jQuery Ajax 函数,但您需要使用 $scope.$apply 包装 DOM 中的任何更改,以使 Angular 了解 jQuery 的操作):

    // within Angular controller
    jQuery.get(url, function(data) {
        $scope.$apply(function() {
            // any DOM changes
        });
    });
    

    但是考虑一下(这将是最好的解决方案)在 Angular 中嵌入 ajax 代码,$http 服务与 jQuery.ajax 并没有太大区别,尤其是如果您熟悉 jQuery Promises。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      相关资源
      最近更新 更多