选择AngularJS中的默认值

时间:2017-11-15 11:51:15

标签: angularjs

嘿我在设置内部数组对象时启动选择问题时设置默认值有问题。我该如何解决这个问题?

HTML

<div ng-app="select" ng-controller="checking">
  <select ng-model="lala" ng-options="item.name for item in arrayName">
  </select>
</div>

的JavaScript

var app = angular.module('select', []);

app.controller('checking', ($scope)=> {
  $scope.arrayName = [{'name':'first'}, {'name':'second'}, {'name':'third'}]; 
  $scope.lala = "first";
});

https://codepen.io/Turqus/pen/EbvGzv?editors=1111

4 个答案:

答案 0 :(得分:1)

您可以尝试以下示例,您必须更改数组位

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
    <select ng-model="prop.value" ng-options="v for v in prop.values">
    </select>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) 
{
    $scope.prop = 
    {
        "type": "select", 
        "name": "Service",
        "value": "first", 
        "values": ['first','second','third'] 
    };
});
</script>

答案 1 :(得分:1)

您需要做的就是更改select as以包含Google Filter Widget - Blank

<select ng-model="lala" ng-options="item.name as item.name for item in arrayName">

var app = angular.module('select', []);

app.controller('checking', function($scope) {
  $scope.arrayName = [{
    'name': 'first'
  }, {
    'name': 'second'
  }, {
    'name': 'third'
  }];

  $scope.lala = 'first';

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="select" ng-controller="checking">

  <select ng-model="lala" ng-options="item.name as item.name for item in arrayName"></select>
  
  <p>Value of lala: <b>{{lala}}</b></p>
  
</div>

答案 2 :(得分:0)

您可以使用下面的ng-init

来实现它
<div ng-app="select" ng-controller="checking">

  <select ng-init="lala = arrayName[0]" ng-model="lala" ng-options="item.name for item in arrayName"  >


  </select>
</div>

<script>
    var app = angular.module('select', []);

    app.controller('checking', ($scope)=> {
      $scope.arrayName = [{'name':'first'}, {'name':'second'}, {'name':'third'}]; 
      $scope.lala = "first";
    });
<script>

这是codepen示例,希望它会有所帮助。

答案 3 :(得分:0)

我认为您只需要像这样分配ng-model。

 $scope.lala = $scope.arrayName[0];

这是您的codepen link