The functionality of Angular.js ajax and apply is experiencing technical difficulties

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;

Answer №1

The reason is that the get_page function does not compile the template. One simple solution (for me) would be to follow these steps: HTML code:

<div ng-app="myApp">
  <div id="main_controler" ng-controller="mainController">
    <button ng-click="get(1)">Page one</button>
    <button ng-click="get(2)">Page two</button><br /><br /><br />

    <div id="content">

      <div ng-show="number==1" ng-repeat="firm in data.firms"  style="width:100%">
        ID: {{firm.id}} Name: {{firm.name}}
      </div>
      <div ng-show="number==2" ng-repeat="person in data.persons"  style="width:100%">
           Name: {{person.name}} Surname: {{person.surname}}
      </div>
    </div>
  </div> 
</div>

JavaScript code:

var app = angular.module('myApp', []);

app.controller('mainController', function($scope, $http) {
  $scope.number = 0;
  $scope.get = function(a_number) {
    $scope.number = 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);
});

Answer №2

The initial answer encountered a minor drawback where the HTML code for listing companies and individuals was retained in the original HTML. Originally, the plan was to dynamically insert this information. After some searching, I found a resolution here:

Compiling dynamic HTML strings from database

I successfully implemented this solution for my specific scenario by shifting templates from JavaScript to the server. Now, the server delivers the HTML via Ajax.

Previously, what I required now looks like this:

HTML snippet:

<body ng-app="app">
  <h1>Compile dynamic HTML</h1>
  <div ng-controller="MyController">
    <button ng-click="get(1)">Page one</button>
    <button ng-click="get(2)">Page two</button><br /><br /><br />
  <!--      <textarea ng-model="html"></textarea>  -->
    <div dynamic="html"></div>
  </div>
</body>

JavaScript snippet:

var app = angular.module('app', []);

app.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});

app.controller('MyController', 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.html = data.template;
       $scope.data = data.data;
    }).error(function(data, status) {
      alert('Error');
    });
  }
  $scope.get(1);
});

PHP snippet:

echo '{"template": "'.get_template($_GET['num']).'", '.
      '"data": '.(get_data($_GET['num'])).'}';  

function get_data($a_template) {
  if ($_GET['num'] == '1') {
    $p_result = '{ "firms": [ { "id": "1", "name": "Apple" },
                    { "id": "2", "name": "Microsoft" } ]}';
  } else if ($_GET['num'] == '2') {
    $p_result = '   { "persons": [ { "name": "Steve", "surname": "Jobs" },
                    { "name": "Bill", "surname": "Gates" } ]}';
  }
  return $p_result;
}

function get_template($a_template) {
  if ($_GET['num'] == '1') {
    $p_result = '<div ng-repeat=\"firm in data.firms\"  style=\"width:100%\"> ID: '.
                                              '{{firm.id}} Name: {{firm.name}}</div>';
  } else if ($_GET['num'] == '2') {
    $p_result =  '<div ng-repeat=\"person in data.persons\"  style=\"width:100%\"> Name: '.
                                 '{{person.name}} Surname: {{person.surname}}</div>';
  }
  return $p_result;
}

I provided an answer to my own inquiry, but I trust that this illustration can assist someone and streamline their process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with jQuery's .height() method not updating

Here is the code I am working with: $(function() { $('#team-ch').click(function() { $('#team-camb-hert').height('auto'); }); }); I am trying to change the height of a div when a link is clicked. After adding an alert ...

Currently exploring AngularJS and looking to create a categorized list

Currently delving into the world of AngularJS, I am embarking on creating a web application. One of my current tasks involves creating a grouped list. I am utilizing a JSON file that contains various entries like: {"title":"videoTitle", "chapter":"2", "s ...

Special character Unicode regex for names

After spending the entire day reading about regex, I am still struggling to fully grasp it. My goal is to validate a name, but the regex functions I have found online only include [a-zA-Z], omitting characters that I need to allow. Essentially, I require ...

I'm having trouble understanding why I can't redirect to my GET router after making a POST request

profile.ejs <body> <div id="box"> <h1>Greetings, <span><%= user.name %></span>!<hr> How are you feeling today?</h1> <!-- <form action="/users/logout" method=" ...

A collection of functions embedded within a JSON data structure

I am working with a website that provides data in a JSON-like format similar to the following: { "name":"tom jones", "no": 123, "storedproc": function(){ callbuyer(0123); } } Currently, I am using $. ...

Using the 'type' field as a parameter in a Vue2 component object

I need help with passing an object into my component. Here is a snippet of the object's properties: { title: "myTitle", type: "myType" } However, when I define the prop in my component like this, I get a Vue runtime warning st ...

Using AJAX in a Django application within a RESTful ecosystem

I am new to the world of restful programming and have a Django website. My goal is to dynamically load a part of the website. Currently, my workflow is as follows: When I call a URL (such as localhost:8080/index), it routes to the Django view, which retr ...

Removing classes from multiple elements on hover and click in Vue 2

Can Vue be used to remove a class from an element? I am looking to remove the class when hovering over the element, and then add it back once the mouse is no longer on the text. Additionally, I want the class to be removed when the element is clicked. He ...

Oops! An error occurred while trying to load the myApp module. The module 'ui.bootstrap' is missing and causing the failure

When using Firefox, I encountered the following error: SyntaxError: syntax error xml2json.js:1 SyntaxError: syntax error ui-bootstrap-tpls-0.13.0.js:1 Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:modulerr] Failed to in ...

Utilizing Dynamic Image Sources in Vue.js with the Help of APIs

Can someone help me figure out how to solve this issue? I have an API that returns a base64 image, and I want to load this image on my site. Any suggestions on where or how I should implement my function? This is the API call located in the methods: metho ...

Unusual behavior involving the selection of $stateParams

Seeking a solution for updating angular-ui route parameters based on select field changes. Issue: The route successfully updates with the selected parameter, but the select field does not reflect the change in option selection. Check out the Plunkr. Clic ...

What is causing the premature termination of the for loop?

I am currently utilizing Node.js (with nodemon as the server) to upload an excel file, parse its contents, and then send each row to a MongoDB database. The total number of rows in the array is 476, however, the loop seems to stop at either 31 or 95 withou ...

Obtain information from YouTube and format it into a list item

Currently, I'm working on compiling a list of videos that includes the title, link, image, and creator of each video. It's been a bit challenging :S <script type="text/javascript"> $(document).ready(function(){ $.getJSON('http://gdata ...

Tips on implementing multiple consecutive setState calls in ReactJS

Recently, I discovered that setState is an async call. I'm facing an issue where I need to utilize the updated result from setState immediately after setting it, but due to its async nature, I end up getting the old state value. While researching for ...

Enhancing the functionality of radio buttons through event changes and optimizing related features

I am searching for a more efficient method to reuse functions that serve a similar purpose. For example, I would like to modify various radio buttons that toggle a hide class on different divs. JSFiddle Link How can jQuery be used to create a reusable fu ...

Testing an ajax-driven website: what's the best approach?

Seeking to develop automated tests for my completely ajax-based website developed using Spring MVC/Java. I possess a basic understanding of Selenium and have managed to create some tests using this tool. The main issue lies in the fact that testing an aja ...

Implementing logic with multiple columns in JavaScript

Looking for a way to display an array of data in multiple columns using Java Script, like this: 1 2 3 4 5 6 7 8 9 instead of 1 4 7 2 5 8 3 6 9 Any suggestions would be greatly appreciated. Thank you. ...

The YouTube Iframe API encountered an issue while attempting to send a message to an HTTP recipient. The recipient's origin

Encountering an error when using the YouTube Iframe API on Safari 9.1, OS X Yosemite Issue: Unable to post message to http://www.youtube.com. Recipient has origin https://www.youtube.com This problem only occurs in Safari, as other browsers like Firefo ...

Ways to dynamically navigate to the end of a webpage following an AJAX request

My jQuery ajax code is functioning properly and displaying the response on the page. However, I am facing an issue with scrolling to the bottom position of the window after displaying the response. To achieve this, I have implemented the following jQuery ...

Tips for expanding an md-nav-item in Angular Material

Need help on stretching the md-nav-item element illustration 1 ------------------------------------------------ | ITEM1 | ITEM 2 | ------------------------------------------------ illustration 2 ------------------------------------------------ | ...