为什么下面的代码在angularjs中对我不起作用

时间:2018-03-21 06:02:18

标签: angularjs ng-options

以下代码是使用提供的json数据填充下拉选择选项。 BUt它没有填充。

                   这不是在函数中使用json数据填充dropdrop     

  <select ng-model="selectedName" ng-options="x for x in values.names">
</select>
<select ng-model="places" ng-options="x for x in values.places"></select>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.values ={
    names :["Emil", "Tobias", "Linus"]
    places :["hyd","tnd","sec"]
    }

});
</script>


<p>This example shows how to fill a dropdown list using the ng-options directive.</p>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

您的JSON应该更正为,

{
  "names": [
    "Emil",
    "Tobias",
    "Linus"
  ],
  "places": [
    "hyd",
    "tnd",
    "sec"
  ]
};

<强>样本

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.values= {
  "names": [
    "Emil",
    "Tobias",
    "Linus"
  ],
  "places": [
    "hyd",
    "tnd",
    "sec"
  ]
};

});
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in values.names">
</select>
<select ng-model="places" ng-options="x for x in values.places"></select>

</div>

答案 1 :(得分:0)

尝试使用此方法填充字段: -

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="myCtrl" ng-app="main">
 <select ng-model="selectedName" ng-options="item.names as item.name for item in values">
    <option value="">Select Account</option>
</select>
<select ng-model="selectedname" ng-options="item.place as item.p for item in values"><option value="">Select Account
</option></select>



<script>
var app = angular.module('main', []);
app.controller('myCtrl', function($scope) {
    $scope.values =[
    { names :1, name: "Email"}, 
    { names :2, name: "Tobias"},
    { names :3, name: "Linus"},
    {place :1, p:"hyd"},
     {place :2, p:"tnd"},
     {place :3, p:"sec"} 
   ];
    // $scope.places=[
    //  {place :1, p:"hyd"},
    //  {place :2, p:"tnd"},
    //  {place :3, p:"sec"} 
    //  ];
    $scope.selectedname=$scope.values[0].names;
    $scope.selectedname=$scope.values[0].place;

});
</script>
</div>