Select,AngularJS中的默认值

e4yzc0pl  于 12个月前  发布在  Angular
关注(0)|答案(5)|浏览(142)

嘿,我有问题,设置默认值在选择问题是开始时,我设置内数组对象。我怎么能解决这个问题??

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

xu3bshqb

xu3bshqb1#

您所需要做的就是将ng-options更改为包含select as

<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>

的数据

w51jfk4q

w51jfk4q2#

你可以尝试下面的例子,你必须改变数组位

<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>

字符串

zazmityj

zazmityj3#

你可以通过使用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的例子,希望它会有所帮助。

dtcbnfnu

dtcbnfnu4#

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

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

字符串
这是你的codepen link

llmtgqce

llmtgqce5#

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

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

字符串

相关问题