Reputation: 143
Can you use angular on dynamic fetched data? I have an existing application where most of the content is rendered by javascript after ajax-call. So I have this div that is filled by fetching data with ajax and then rendered by javascript. Well, in all these lot of html that is fetched by ajax, if I use ng-app on one of this elements, it doesnt seem to work. Doing the same thing with an html-element that has been fetched in the initial request (prior to the ajax-request) works.
So here is the code:
File: test.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" ng-app>
<head>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="ang_app.js"></script>
<script>
$( document ).ready(function() {
$.ajax({
url: "test2.php"
}).success(function(data) {
$('#content').html(data);
});
});
</script>
<body>
<h2>This is an app</h2>
<div ng-app ng-controller="StatsCtrl2">StatsCtrl2</div>
<div id="content"></div>
</body>
</html>
File test2.php:
<?php
echo '<div style="background-color:green;" ng-app ng-controller="StatsCtrl">Should be StatsCtrl</div>';
File ang_app.js:
function StatsCtrl($scope){
alert("function StatsCtrl");
}
function StatsCtrl2($scope){
alert("function StatsCtrl2");
}
Well, running this app I see the alert for "StatsCtrl2". But the alert inside "StatsCtrl" never shows app. Am I doing something wrong?
Upvotes: 1
Views: 360
Reputation: 10153
(1) AngularJS runs on $(document).ready
.
That means by the time the AJAX response comes ng-controller="StatsCtrl2"
is already bound to that DIV.
(2) As I said in (1), AngularJS parses the directives in your HTML on DOM ready. You need to $compile
the HTML you are injecting afterwards.
(3) You are adding ng-app
and ng-controller
inside existing ng-app
and ng-controller
. When you fix all the other issues this will most probably cause some more issues.
You are taking a bad approach to this. In normal circumstances you only have access to AngularJS built-in stuff inside services, controllers, directives and so on. I'm specifying this because the solution to your problem would be to
$.ajax({
url: "test2.php"
}).success(function(data) {
$('#content').html(data);
$compile($('#content'))($scope);
});
but there's no $compile
or $scope
there. Those only exist inside the AngularJS Application.
You need to stop using jQuery and start using actual AngularJS constructs specifically designed for this: a controller together with $http
or maybe ng-include
.
Then you won't have to worry about (2) and (3).
I repeat: AngularJS is not intended to be used the way you are using it. You will only get into further trouble later on if you somehow hack what you have and make it work.
Upvotes: 1