我有一个选择
data-ng-model="layout" ng-options="layout.url as layout.name for layout in layouts"
从外部json文件填充:
{
"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"
}
和控制器
function httpController($scope, $http) {
$http.get('content.json').success (function(data){
$scope.layouts = data.layout;
$scope.layout = $scope.layouts[2];
});
};
$scope.layout = $scope.layouts[2];
应设置为默认值,但不起作用。
如果JSON数组在控制器中,但是我需要在外部JSON中使用它,它似乎工作正常;
任何帮助都将不胜感激。
答案 0 :(得分:1)
您只需将.url
添加到$scope.layout = $scope.layouts[2];
在$http.get()
执行以下操作。
$http.get('URLToGET')
.success(function(data){
$scope.layouts = data.layout;
$scope.layout = $scope.layouts[2].url; //<--- .url
});
您的HTML将如下所示:
<select data-ng-model="layout" ng-options="layout.url as layout.name for layout in layouts">
<option value="">Select Url</option>
</select>
这是一个新的更新工作示例
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>
有些澄清
当您使用
ng-options
时,选项标签的值会被写出来 ng-options将始终是选项标记的数组项的索引 涉及到。这是因为Angular实际上允许您选择 具有选择控件的整个对象,而不仅仅是基本类型。
有关ngOptions
以及great answer by Ben Lesh的详细信息,请参阅ngOptions official docs。
答案 1 :(得分:0)
修改你的ng-options,如下所示:
ng-options="layout as layout.name for layout in layouts"
您的ng-options表达式采用以下格式:
选择为数据
中的值 标签根据角度文档,选择的定义是:
此表达式的结果将绑定到父级的模型 元件。如果未指定,则选择表达式将默认为 值。
您将url属性绑定到模型而不是整个对象。这就是问题所在。