I'm new to AngularJS, so bare with me. Firstly, I'm using AngularJS in parts of my website, not for the whole thing. I have a couple of select boxes with one that is dependent on the other. One contains a list of countries, and the other contains cities for the selected country.
In the past, I would split my json into 2 queries to the server, so on country changed, it'll send the selected value, and the server would return a json list accordingly which will be inserted into the select box using jquery. This time, and using http://builtwith.angularjs.org/ as sort of a guideline, I decided to return everything as one json, and handle this functionality purely in javascript.
So lets say, my json looks like this:
[
{ "code": 1, "country": "Germany", "cities": [ "Berlin", "Munich" ] },
{ "code": 2, "country": "Italy", "cities": [ "Rome", "Venice" ] },
{ "code": 3, "country": "United Kingdom", "cities": [ "London", "Manchester" ]}
]
I would need all the values of country as one list for country select box, and the list of each cities for the other select box.
Here's the controller so far:
angular.module('myApp', [])
.controller('MyController', ['$scope', '$http', function ($scope, $http) {
$http.get('/api/locations')
.success(function (data, status, header, config) {
$scope.locations = data[0];
$scope.countryList = [];
$scope.cityList = [];
for (var i = 0; i < data.length; i++) {
$scope.countryList.push([data[i].code, data[i].country]);
for (var j = 0; j < data[i].cities.length; j++) {
$scope.cityList.push([data[i].code + '-' + data[i].cities[j], data[i].cities[j]]);
}
}
});
}]);
My select boxes:
Country:
<select ng-model="country" data-ng-options="c for c in countryList"></select>
City:
<select data-ng-model="city" data-ng-options="c for c in cityList"></select>
Currently, both select boxes get filled, but their text contains both values of the array. The cities box contains ALL cities, not just the ones for the first country.
I'm not sure if i'm on the right path here, or if there's an easier way to achieve this.
So sum up, I'd like to know:
- Should i keep the whole json as one request/response and handle it in JS?
- How do you load each select box the 'official' angularjs way?
- I'm aware of the ng-change attribute on the select box, but I'm not sure how I'd create a query and change the city list values according to the selected country.
Here is a plunk: http://plnkr.co/edit/zAcRjSDm9OndxugtsAOs?p=preview
Thanks!