2

I have some markup and loaded controllers.

Then I load some modal window contents by ajax, which is using one of controllers I have defined before. But looks like this controller isn't being used, because he is not required until modal loaded.

Question: How to make controller work when modal loaded? I tryied $scope.$digest(), got error "digest in progress".

index.html

<html data-ng-app="foo">
<head>
<script src="/js/app.js"></script>
</head>
<body>
<div id="modal"></div>
</body>
</html>

js/app.js

!(function(){
    function FormCtrl($scope) {
        console.log($scope); // never fired

        $scope.Submit = function() {
            console.log('submit'); // never fired too :C
        }
    }

    angular.module('foo', []).controller('FormCtrl', FormCtrl);
})();

html content loaded by ajax and inserted to #modal

<div data-ng-controller="FormCtrl">
<form name="signup" data-ng-submit="Submit()">
<!-- form data -->
</form>
</div>

SOLUTION:

$.modal().open({
    onOpen: function($e) {
        $http.get('/views/' + url).success(function(data) {
            $compile(data)($scope, function(clonedElem) {
                $e.html(clonedElem);
            });

            // $e.html(data); was used instead of statement above
        });
    }
});
4
  • Can you tell what this modal window content is? Is the html for this modal window being retrieved by ajax? Commented Sep 6, 2013 at 10:55
  • Yes, html content with form. Commented Sep 6, 2013 at 10:58
  • Does your ng-controller is within your AJAX HTML code? Commented Sep 6, 2013 at 11:05
  • I will add code samples. Commented Sep 6, 2013 at 11:07

1 Answer 1

1

If you want to inject new DOM elements into existing Anuglar app. You options are to use

  • ng-include: This has a src property that takes the url from which partial content has to be loaded. AngularJS would internally compile it. One important thing here is that angular will download the template as soon it encounter ng-include in html.
  • Download and compile DOM manually using the $compile service which is a more involved process.

If your AJAX content contains a controller defined in ng-controller, AngularJS would create it for you.

But in any case, keep in mind the controller script should have been already wired at the initialization\setup phase.

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

3 Comments

Could you please explain? I need to call $compile($('#modal')) after loading html content?
Yes, and then add it some specific location with the DOM. Something like this stackoverflow.com/questions/11699635/…
Thanks you a lot! I did things that I wanted.

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.