如何在AngularJS中使用脚本标记获取动态内容?

时间:2016-10-17 17:02:44

标签: angularjs angularjs-compile

我正在尝试将AngularJS集成到现有的Web应用程序中。应用程序中的某些数据是通过$.ajax()element.html(data)动态加载的。 data可以包含带有标记<script>中的javascript代码的html代码。此代码由浏览器成功加载,但当我尝试调用$compile()时,有角度的人不会看到它。我该如何解决这个问题?

JSFiddle

<div ng-app="app">
    <div id='container'>

    </div>
</div>
var app = angular.module('app', []);

$(document).ready(function() {
    var container = $('#container');
    var html = '';
    html += '<scripttag type="text/javascript">';
    html += 'app.controller("TestController", function($scope) {$scope.testVar = "testVal"});';
    html += 'console.log("Controller added");';
    html += '</scripttag>';
    html += '<b ng-controller="TestController">{{testVar}}</b>';
    container.html(html.replace(/scripttag/g, 'script'));

    angular.element(container).injector().invoke([ '$compile', function($compile) {
            var $scope = angular.element(container).scope();
            console.log("Compiling new element...");
            $compile(container)($scope);
            $scope.$apply();
    } ]);
});

控制台日志:

Controller added
Compiling new element...
Uncaught Error: [ng:areq] Argument 'TestController' is not a function, got undefined http://errors.angularjs.org/1.2.30/ng/areq?p0=TestController&p1=not%20a%20function%2C%20got%20undefined

PS html.replace(/scripttag/g, 'script') - 是解决方法,因为html('<script></script>')无法直接调用jsffidle.com。

1 个答案:

答案 0 :(得分:0)

好的,问题是,在你的AngularJS应用程序被引导后,你无法定义新的控制器。 Description and solution

我修复了我的示例here

    app.config(
        function( $controllerProvider, $provide, $compileProvider ) {
            app._controller = app.controller;
            app._service = app.service;
            app._factory = app.factory;
            app._value = app.value;
            app._directive = app.directive;
            app.controller = function( name, constructor ) {
                $controllerProvider.register( name, constructor );
                return( this );
            };
            app.service = function( name, constructor ) {
                $provide.service( name, constructor );
                return( this );
            };
            app.factory = function( name, factory ) {
                $provide.factory( name, factory );
                return( this );
            };
            app.value = function( name, value ) {
                $provide.value( name, value );
                return( this );
            };
            app.directive = function( name, factory ) {
                $compileProvider.directive( name, factory );
                return( this );
            };
        }
    );