我有一个应用程序,我正在其中异步加载登录模式,因此它可以跨组成该应用程序的多个平台使用。我正在加载并绑定(bind)模态的 HTML,但在异步加载模态后,我找不到初始化模态中的 Angular Controller 的方法。基本思想如下:
<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,而是通过服务加载。这是一个 super 简化的版本,因为制作 JSBins 需要大量时间。
最佳答案
如果我理解正确,您需要将加载的 HTML 附加到 Controller 的范围。我认为最简单的方法是创建一个自定义指令来加载 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);
}
};
});
编辑:
经过一番思考,您也许可以使用 ng-include 而不是 ng-bind-html,但这确实取决于您加载 HTML 的方式。
关于javascript - Angular.js : Initializing a controller on an asynchronously loaded template?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27461184/