As I venture into the world of angular.js, I am facing a challenge with displaying the correct content on my website. The pages' content is fetched via AJAX (currently from static data, but eventually from a database). When I place a block with the ng-repeat directive inside an element with the id "content", everything functions as expected. The result is:
ID: 1 Name: Apple ID: 2 Name: Microsoft
However, when I dynamically inject the element into the content using JavaScript and AJAX, I encounter difficulties in displaying the correct data. The result becomes:
ID: {{firm.id}} Name: {{firm.name}}
I attempted to use setTimeout() to subsequently call $apply(), but it wasn't successful. I searched online for a solution, but could not find a similar example. Does anyone have any insights on where the issue might be originating from? Thank you in advance for your assistance.
Here is the HTML code snippet:
<div ng-app="myApp">
<div id="main_controler" ng-controller="mainController">
<button onclick="get_page('1')">Page one</button>
<button onclick="get_page('2')">Page two</button><br /><br /><br />
<div id="content">
<div ng-repeat="firm in data.firms" style="width:100%">
ID: {{firm.id}} Name: {{firm.name}}
</div>
</div>
</div>
</div>
And the corresponding JavaScript code section:
var app = angular.module('myApp', []);
app.controller('mainController', function($scope, $http) {
$scope.get = function(a_number) {
var p_url = 'ajax_fce.php?num=' + a_number;
$http({
method: 'JSON',
url: p_url
}).success(function(data, status) {
$scope.data = data;
}).error(function(data, status) {
alert('Error');
});
}
$scope.get(1);
});
get_template_1 = function() {
return '<div ng-repeat="firm in data.firms" style="width:100%">'+
'ID: {{firm.id}} Name: {{firm.name}}'+
'</div> ';
}
get_template_2 = function() {
return '<div ng-repeat="person in data.persons" style="width:100%">'+
'Name: {{person.name}} Surname: {{person.surname}}'+
'</div> ';
}
load_template = function(page_id) {
var p_template = '';
if(page_id == 1) { p_template = get_template_1(); }
if(page_id == 2) { p_template = get_template_2(); }
return p_template;
}
get_page = function(page_id) {
$('#content').html(load_template(page_id));
angular.element(document.getElementById('main_controler')).scope().get(page_id);
angular.element(document.getElementById('main_controler')).scope().$apply();
}
Last but not least, here is the PHP code used for AJAX communication:
$p_return = '';
if ($_GET['num'] == '1') {
$p_return = '{ "firms": [ { "id": "1", "name": "Apple" },
{ "id": "2", "name": "Microsoft" } ]}';
}
else if ($_GET['num'] == '2') {
$p_return = '{ "persons": [ { "name": "Steve", "surname": "Jobs" },
{ "name": "Bill", "surname": "Gates" } ]}';
}
echo $p_return;