2

I have an application where I'm loading a login modal asynchronously so it's available across the multiple platforms that make up the application. I'm loading and binding the HTML for the modal, but I can't find a way to initialize the Angular controller that is IN the modal after loading it asynchronously. Here's the basic idea:

<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>

Note, I'm not actually using ng-init, I'm loading via a service. This is a super-dumbed-down version because making JSBins takes a poopload of time.

1 Answer 1

2

If I understand correctly, you need to attach the loaded HTML to the controller's scope. I think the easiest way is to create a custom directive that will load the HTML, "compile" it and attach it to the modal.

Here is a simple example:

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

EDIT:

After some thought, you might be able to just use ng-include instead of ng-bind-html, but it does depend on how you load the HTML.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.