2016-10-17 92 views
0

我正在尝试将AngularJS集成到现有的Web应用程序中。应用程序中的一些数据通过$.ajax()element.html(data)动态加载。 data可以包含代码为<script>的javascript代码的html代码。此代码由浏览器成功加载,但当我尝试拨打$compile()时,角度不会看到它。我怎样才能解决这个问题?如何在AngularJS中使用script标签获取动态内容?

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的。

回答

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); 
      }; 
     } 
    );