How to load an ng-controller through ajax and inject it into the DOM

Asked

Viewed 480 times

1

I am creating an application where I would like to load my modules through ajax. This application uses Angularjs to do the treatment of each module and these are injected into my DOM using Jquery, as in the example below:

EDIT - (as requested by @Eduardobinoto)

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.min.js"></script>
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    </head>
    <body ng-app="app">

        <section name="foo" ng-controller="fooCtrl">
            <button ng-click="bar()">my name is foo</button>
        </section>

        <script>
          angular.module('app',[])
            .controller('fooCtrl', ['$scope','$http', '$compile', function($scope, $http, $compile) {
                $scope.bar = function(){
                    //simulação de requisição $http que retornou um módulo
                    var ajaxResponse = 
                        '<section name="bar" ng-controller="barCtrl">'+
                            '<button ng-click="helloWorld()">hello world</button>'+
                        '</section>';
                    //inserção do conteúdo no body através do jQuery
                    $('body').append(ajaxResponse);
                    //compilação do novo controller
                    $compile($('body'),$scope);
              };
            }])
            .controller('barCtrl', ['$scope', function($scope) {
                $scope.helloWorld = function(){ alert('Hello World!!!'); };
            }])
        ;
        </script>
    </body>
</html>

I need to know how I can make the angular view this new module after insertion through jquery.

NOTE: I searched various contents on the internet and all say I need to run a $scope.$apply or a $scope.$digest but I couldn’t understand in any of the examples that I found how to really use this in this situation.

3 answers

3

Good morning, to work what you are wanting to do, you must use $compile() angular.

Example:

var mainMod = angular.module('MainApp', []);
mainMod.controller('MainCtrl', ['$scope','$compile',


 var ajaxResponse =  '<section name="bar" ng-controller="barCtrl">'+
                        '<button ng-click="helloWorld()">hello world</button>'+
                     '</section>';

 //inserção do conteúdo no body através do jQuery
 $('body').append(ajaxResponse);

 //$compile
 $scope.compile = $compile(ajaxResponse)($scope);


    }
]);

I hope I’ve helped.

  • guy tried to do the way you put it but it didn’t work. even I called the $compile and executing it at the end of my function the same did not cause the ng-controller="barCtrl" be read and interpreted...

  • 1

    You can post your code in full so I can view it, as I’m sure $Compile will meet your demand. Att, Binotto

  • It may be trivial but since it still didn’t work check if your barCtrl is accessible in the page scope, I mean, if it is loaded in the page.

1

If you only use $(). append() you will only be including the string in html and not updating the DOM.

There is a directive that does all this work p/ we developers.

app.directive('dynamic', ['$compile', function($compile){
return{
  replace: true,
  link: function($scope, ele, attrs) {
      $scope.$watch(attrs.dynamic, function(html){
         if(!html)
            return;
         ele.html((type of(html) === 'string') ? html : html.data);
         $compile(ele.contents())($scope);
});
}
}
}]);

After adding the directive to call just you put.

<div data-dynamic="htmlDynamic" ></div>

in your controller you just need to implement

$scope.htmlDynamic = "HTML AQUI";
  • i tried using the above directive as a test but it also didn’t work.

  • You can send me how you did the implementation ?

1


  1. Need to compile the HTML dynamic before adding it to the DOM by Jquery
  2. When compiling you need to specify the scope in which the provided HTML will be compiled because $Compile returns a function that waits for context

Thus the solution of the problem is as follows:

var ajaxResponse = '<section name="bar" ng-controller="barCtrl">'+
                        '<button ng-click="helloWorld()">hello world</button>'+
                    '</section>';

//COMPILE ANTES DE COLOCAR NO DOM Fornecendo o escopo                  
var compiled = $compile(ajaxResponse)($scope);

$('body').append(compiled);

Follow the plunker: HERE

  • 1

    THANKS MANIN! WAS ALL I NEEDED!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.