簡體   English   中英

給定AngularJS中的模板和控制器實例,如何使用它的控制器實例編譯模板?

[英]Given a template and a controller instance in AngularJS, how can I compile the template in a way that it uses my controller instance?

我有一個模板和一個控制器實例。 該模板上沒有 ng-controller指令。 我想以使用我提供的控制器實例的方式來編譯模板。 這是我到目前為止的代碼:

var scope = $scope.$new();
var template = $templateCache.get('path/to/template.tpl.hml');
var controller = $controller('SomeController', {
    $scope: scope,
    foo: { ... },
    bar: { ... }
});
var html = $compile(template)(scope);

// Doesn't work correctly because the template has no controller.
scope.$apply();

對於那些想知道為什么為什么要首先這樣做的人 :我有一個使用ui-bootstrap $ modal service在模式下彈出的窗體。 我傳遞給$ modal的參數是:模板URL,控制器名稱和包含一堆我想注入到控制器中的數據的對象(有關更多信息,請參見鏈接的文檔)。 $ modal服務負責實例化控制器,將我的數據注入到控制器,編譯模板,並將所有這些信息粘貼到Bootstrap模態對話框中。 由於$ modal必須將內容注入控制器,因此模板上不能具有ng-controller屬性。

彈出模態在我的應用程序中可以正常工作,因為$ modal在幕后發揮了魔力,並以某種方式讓我的模板知道應該使用哪個控制器,但是當我編寫單元測試時,事情並不是那么樂觀。

在測試中,我想使用$ compile服務自行編譯模板。 這使我可以輕松訪問表單的范圍和DOM樹。 當然,我無法執行此操作,因為我無法弄清楚$ modal在后台執行的操作。

任何人?

通過查看ng-controller的源代碼 ,您會看到它是一個非常簡單的指令:

var ngControllerDirective = [function() {
  return {
    scope: true,
    controller: '@',
    priority: 500
  };
}];

因此,$ modal中的魔術可能相似。 創建自己的ng-controller以進行測試(甚至用於生產)很容易。 然后可以在測試中使用:

$scope = $rootScope.$new();
var template = '<div my-controller="ctrl1">{{x}}</div>'
html = $compile(template)($scope);
$scope.$apply();

ctrl1僅用於測試。 請參見此處

但這可能超出您的需要。 在測試中,為什么不在運行時僅添加ng-controller

$scope = $rootScope.$new();
var template = '<div>{{x}}</div>'
html = $compile(template)($scope);
html.attr('ng-controller', 'ctrl1');
html = $compile(html)($scope);
$scope.$apply();

請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM