2016-10-17 86 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); 
      }; 
     } 
    );