javascript - Angular.js : Initializing a controller on an asynchronously loaded template?

标签 javascript angularjs asynchronous

我有一个应用程序,我正在其中异步加载登录模式,因此它可以跨组成该应用程序的多个平台使用。我正在加载并绑定(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);
        }
    };
});

DEMO

编辑:

经过一番思考,您也许可以使用 ng-include 而不是 ng-bind-html,但这确实取决于您加载 HTML 的方式。

关于javascript - Angular.js : Initializing a controller on an asynchronously loaded template?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27461184/

相关文章:

javascript - 当从 JavaScript 中的外部文本文件读取时,如何正确显示国家标志(UTF-8)?

javascript - 使用 "addfeature"加载多边形中的孔

javascript - 通过右键单击转到链接

javascript - AngularJS : factory $http. get 请求不断获取 html 文件作为返回

angularjs - Jasmine spy 方法返回未定义

django - Tornado 还是 Node ? express 呢? Node Django?

javascript - 使用 Function.prototype.bind() 部分应用 mkdirp

javascript - AngularJS:如何在单击时将事件类设置为列表项?三元法

Javascript 使用 Promises 为 For 循环的每个项目运行异步代码

javascript - NodeJS Express Route 在渲染的路由中返回异步数据