Here's a simple example of how to load JSON data into an Angular model.
I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.
http://www.iNorthwind.com/Service1.svc/getAllCustomers
It returns some JSON data which looks like this:
{
"GetAllCustomersResult" :
[
{
"CompanyName": "Alfreds Futterkiste",
"CustomerID": "ALFKI"
},
{
"CompanyName": "Ana Trujillo Emparedados y helados",
"CustomerID": "ANATR"
},
{
"CompanyName": "Antonio Moreno TaquerÃa",
"CustomerID": "ANTON"
}
]
}
..and I want to populate a drop down list with this data, to look like this...
I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.
How would I do it ?
My Angular controller would look like this:
function MikesAngularController($scope, $http) {
$scope.listOfCustomers = null;
$http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
.success(function (data) {
$scope.listOfCustomers = data.GetAllCustomersResult;
})
.error(function (data, status, headers, config) {
// Do some error handling here
});
}
... which fills a "listOfCustomers" variable with this set of JSON data.
Then, in my HTML page, I'd use this:
<div ng-controller='MikesAngularController'>
<span>Please select a customer:</span>
<select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>
And that's it. We can now see a list of our JSON data on a web page, ready to be used.
The key to this is in the "ng-options" tag:
customer.CustomerID as customer.CompanyName for customer in listOfCustomers
It's a strange syntax to get your head around !
When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.
The full script for this example can be found here:
Mike