设置选择的某些选项

时间:2018-06-21 15:09:22

标签: angularjs

我正在尝试更新表中的一行,因此在编辑模式下,我需要获取现有数据并将其填充到卡中。文本框很好,但选择麻烦。我无法获得选择以显示已获取的现有选项。

我的标记:-

    <select class="textbox-style4" data-ng-options="obj.text for obj in segment track by obj.value" data-ng-model="u_segment">
                                    </select>

这是我初始化选择的方式:-

    $scope.segment = [ {
        "text" : "B2B",
        "value" : "0"
    }, {
        "text" : "B2C",
        "value" : "1"
    } ];

这是我尝试设置其值的方法(尝试了两种方式):- 1)

    $scope.u_segment = selected.segment;

2)

    $scope.u_segment.value = selected.segment;

但是,尽管已填充其他(文本字段),但它(选择)仍然保持空白。

1 个答案:

答案 0 :(得分:1)

您正在选择obj,因此您的selected.segment必须是整个对象:{"text" : "B2B", "value" : "0"}(例如)

这是一个演示:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

  var selected = {
    "segment": {
      "text": "B2C",
      "value": "1"
    }
  };

  $scope.segment = [{
    "text": "B2B",
    "value": "0"
  }, {
    "text": "B2C",
    "value": "1"
  }];
  
  $scope.u_segment = selected.segment;
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">

    <select class="textbox-style4" data-ng-options="obj.text for obj in segment track by obj.value" data-ng-model="u_segment">
    </select>
    {{u_segment}}

  </div>

</body>

</html>


如果您不了解整个对象,但仅了解它的某些属性(例如value),则需要(循环)搜索它:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

  var selected = {
    "segment": "0"
  };

  $scope.segment = [{
    "text": "B2B",
    "value": "0"
  }, {
    "text": "B2C",
    "value": "1"
  }];
  
  for(var i=0; i<$scope.segment.length; i++){
    if($scope.segment[i].value == selected.segment){
      $scope.u_segment = $scope.segment[i];
    }
  }
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>
  <div ng-app="myApp" ng-controller="myCtrl">

    <select class="textbox-style4" data-ng-options="obj.text for obj in segment track by obj.value" data-ng-model="u_segment">
    </select>
    {{u_segment}}

  </div>

</body>
</html>