Loading Partial Page With Angular and Compile The Controller

前端 未结 2 566
再見小時候
再見小時候 2020-12-29 15:41

In large scale application, our web application might be organize into separate partial page in order to increase the modularity of our application. In some case compiling a

2条回答
  •  情书的邮戳
    2020-12-29 16:15

    If I understand what you are trying to do, here's a simple example.

    I wanted to post via AJAX to a Django form and then replace the form content in the page with the returned markup. The returned markup includes an ng-controller, which I need to execute when it loads:

    .controller('MyForm', function($element, $compile, $scope){
        var scope = $scope;
        var $theForm = $element;
        var $formBlock = $element.find('.the_form');  // is replaced by the form response
        $element.find('.submit_the_form').click(function(){
            // submit the form and replace contents of $formBlock
            $.post($theForm.attr('action'), $theForm.serialize(), function(response){
                var newstuff = $formBlock.html(response);
                $compile(newstuff)(scope); // loads the angular stuff in the new markup
            });
        });
    })
    

    I think the line you're interested in is $compile(newstuff)(scope);

    EDIT: Crikey, tried this with some other markup this morning and did not work, for no reason I could figure out. Turned out that if I did not have a field with ng-model assigned, in the new markup, then the $compile does not execute. Added:

    
    

    ...and now it compiles.

提交回复
热议问题