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.
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 theng-controller="barCtrl"
be read and interpreted...– LeandroLuk
You can post your code in full so I can view it, as I’m sure $Compile will meet your demand. Att, Binotto
– Eduardo 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.
– Giovanni Silva