2014-12-13 71 views
2

我有一個應用程序,我異步加載登錄模式,因此它可以在構成應用程序的多個平臺上使用。我正在加載和綁定模態的HTML,但我找不到一種方式來初始化異步加載模態中的Angular控制器。這裏的基本思想是:Angular.js:在異步加載的模板上初始化控制器?

<div ng-controller="loginController" ng-init="loadModal()"> 
    <a ng-click="openModal()">LOG IN</a> 
    <div ng-bind-html="modalHTML"> 
     // Once loaded, I need to initialize the AngularJS in here, fr'ex: 
     <ul> 
      <li ng-repeat="item for item in items>{{item.blerg}}</li> 
     </ul> 
    </div> 
</div> 

注意,我不是在實際使用NG-INIT,我通過服務加載。這是一個超級笨拙的版本,因爲使JSBins花費了大量的時間。

回答

2

如果我理解正確,您需要將加載的HTML附加到控制器的作用域。我認爲最簡單的方法是創建一個自定義指令來加載HTML,「編譯」它並將其附加到模態。

下面是一個簡單的例子:

HTML

<div ng-controller="loginController"> 
    <div async-modal> 
    </div> 
</div> 

JS

angular.module('test', []).controller('loginController', function ($scope) { 
    $scope.items = ['one', 'two', 'three']; 
}).directive('asyncModal', function ($compile, $timeout) { 
    return { 
     restrict: 'A', 
     scope: false, 
     link: function (scope, element) { 
      // $timeout is here just to emulate async behaviour 
      // this should be your loader service 
      $timeout(function() { 
       // lets assume that this is the loaded HTML 
       var html = '<ul><li ng-repeat="item in items">{{item}}</li></ul>'; 
       element.append($compile(html)(scope)); 
      }, 1000); 
     } 
    }; 
}); 

DEMO

編輯:

索姆後我想,你可能只需要使用ng-include而不是ng-bind-html,但是這取決於你如何加載HTML。