Angular.js:在异步加载的模板上初始化控制器?

问题描述:

我有一个应用程序,我异步加载登录模式,因此它可以在构成应用程序的多个平台上使用。我正在加载和绑定模态的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花费了大量的时间。

如果我理解正确,您需要将加载的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。