I have a select
data-ng-model="layout" ng-options="layout.url as layout.name for layout in layouts"
populated from an external json file:
{
"metaDescription": "My website description",
"metaKeywords": "keyword1, keyword2",
"siteTitle": "My Company",
"pageTitle": "Welcome ",
"layout": [
{ "name": "Cerulean", "url": "cerulean" },
{ "name": "Cosmo", "url": "cosmo" },
{ "name": "Cyborg", "url": "cyborg" }
],
"test": "Lorem ipsum dolor"
}
And a controller
function httpController($scope, $http) {
$http.get('content.json').success (function(data){
$scope.layouts = data.layout;
$scope.layout = $scope.layouts[2];
});
};
The $scope.layout = $scope.layouts[2];
should set as the default value but it does not work.
It seems to be working if the JSON array is in the controller but I need to use it from an external JSON and in this case it does not work!
Any help would be appreciated.
You just need to add .url
to your $scope.layout = $scope.layouts[2];
In your $http.get()
Do the following.
$http.get('URLToGET')
.success(function(data){
$scope.layouts = data.layout;
$scope.layout = $scope.layouts[2].url; //<--- .url
});
Your HTML will look like this:
<select data-ng-model="layout" ng-options="layout.url as layout.name for layout in layouts">
<option value="">Select Url</option>
</select>
Here is a new updated working example
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.data = {
"metaDescription": "My website description",
"metaKeywords": "keyword1, keyword2",
"siteTitle": "My Company",
"pageTitle": "Welcome ",
"layout": [
{ "name": "Cerulean", "url": "cerulean" },
{ "name": "Cosmo", "url": "cosmo" },
{ "name": "Cyborg", "url": "cyborg" }
],
"test": "Lorem ipsum dolor"
};
$scope.layouts = $scope.data.layout;
$scope.layout = $scope.layouts[2].url;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<select ng-model="layout" ng-options="layout.url as layout.name for layout in layouts">
<option value="">Select Url</option>
</select>
<label ng-bind="layout"></label>
</div>
</div>
For Some clarification
When you use
ng-options
, the values of option tags written out by ng-options will always be the index of the array item the option tag relates to. This is because Angular actually allows you to select entire objects with select controls, and not just primitive types.
Refer to a great answer by Ben Lesh for details on ngOptions
as well as the ngOptions official docs.