Here’s an example.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="myController"> <div ng-repeat="birds in list"> {{ birds }} </div> </div> </body> <script> const myApp = angular.module('myApp', []); myApp.controller('myController', function ($scope, $http) { let arr = new Array(); $http.get("../../library/birds.xml").success(function (xml) { $(xml).find('Bird').each(function () { arr.push($(this).find('name').text()) }); $scope.list = arr; }).error(function (status) { alert(status); }); }); </script> </html>
In the above example, I am extracting data from an XML file, named birds.xml. I have declared the $scope along with $http.
The $http.get() method makes a request for the data. If the request is successful, it will loop through each node and fills the array with data.
The data in the array (arr) is delivered to a the model via $scope.
$scope.list = arr;
Now see the model, I am displaying data in a <div> element using ng-repeat directive.
<div ng-repeat="birds in list">
{{ birds }}
</div>
Its very simple.
Populate XML data using <ul>
Similarly, you can populate data into an <ul> list, instead of the <div> element (as shown in the above example).
<ul ng-repeat="birds in list">
<li>{{ birds }}</li>
</ul>
The script remains the same (see the 1st example). The model has changed slightly. However, here too I am using the ng-repeat directive to show the data.
Populate XML data into a SELECT dropdown
In-addition, you can populate SELECT dropdown list using the above methods. The Ajax call remains the same. There will be a slight change in the model.
In this example, I am using the ng-options directive to fill the dropdown list with the data.
<select ng-model="your_selection" ng-options="b for b in list">
<option value="">-- Select a Bird --</option>
</select>
<!-- show what you have selected -->
<p>You have selected: {{ your_selection }}</p>
Making an Ajax call in AngularJS is very simple. The $http service provides all the necessary properties and method, which makes communication with server properties easy. In the above examples, I have used $http service to access XML data from a remote file. Similarly, you can read or extract data from other popular data sources like a JSON file. See this post.