javascript - $targetDom.html(...).scope 不是函数

标签 javascript angularjs

我正在尝试通过 AJAX 加载动态 HTML 内容,然后编译它,因为它包含使用 angularJS class 的 Angular Directive(指令).

// Class
var AngularHelper = (function () {
    var AngularHelper = function () { };
    var defaultApplicationName = "MyApp";
    /**
     * Compile : Compile html with the rootScope of an application
     *  and replace the content of a target element with the compiled html
     * @$targetDom : The dom in which the compiled html should be placed
     * @htmlToCompile : The html to compile using angular
     * @applicationName : (Optionnal) The name of the application (use the default one if empty)
     */
    AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
        var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
        $injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
            //Get the scope of the target, use the rootScope if it does not exists
            var $scope = $targetDom.html(htmlToCompile).scope();
            $compile($targetDom)($scope || $rootScope);
            $rootScope.$digest();
        }]);
   }

    return AngularHelper;
})();

// jQuery
$(document).ready(function(){
  $.get( "http://fuiba.com/test/index.html", function( data ) {
    $("#result").html(data);
    AngularHelper.Compile($("#result"), data);
  });
});

// Angular
angular.module('MyApp',[]).controller('AppCtrl', function ($scope) {
  /**/
});

但我收到此错误( see this codepen ):

$targetDom.html(...).scope is not a function

最佳答案

使用angular.element($targetDom).scope();代替$targetDom.html(htmlToCompile).scope();

关于javascript - $targetDom.html(...).scope 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36289814/

相关文章:

angularjs - 显示隐藏 Div AngularJs

javascript - Express 路由与 AngularJS 路由冲突。

javascript - 使用 ng-if 获取 ui-router 的当前状态

javascript - 如何为对象数组提供 ng-options?

javascript - 如何将属性传递给 Backbone View ?

css - 无法调用 Controller 构造函数和提交函数

javascript - Angular + Selenium : Cannot get value from input field

javascript - 根据输入将用户定向到两个不同的 URL

javascript - HTML 文本编辑器 div - 强制文本从底部开始 - 从下到上文本框

javascript - 使用 .affix 和固定导航栏的侧边栏偏移