Miraage
Miraage

Reputation: 3464

Angular.js: How to reload scope?

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
        });
    }
});

Upvotes: 2

Views: 4583

Answers (1)

Chandermani
Chandermani

Reputation: 42669

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.

Upvotes: 1

Related Questions