Angular:在下拉列表中设置默认值

时间:2015-12-10 05:49:53

标签: angularjs

我已经设置了一个基本低于代码的plunker。 我无法在下拉列表中看到默认值[银行帐号]被选中。我看到该模型正在更新。但由于某些原因,我的默认值不会被选中。有人能帮助我吗?

//index.html
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js" data-semver="1.0.7"></script>
  <script src="script.js"></script>
  <script src="services.js"></script>
</head>

<body ng-controller="homeCtrl">
  <h1>Other Criteria: {{ otherCriteria.optionText }}</h1>
  <div>
    <select data-ng-model="otherCriteria"
      data-ng-options="o as o.optionText for o in criteria">
    </select>
  </div>
</body>

</html>

//services.js
app.factory("homeService", [
  "$q",
  function($q) {
    function _getDropdownValues() {
      var deferred = $q.defer();

      var dropdownValues = [{"optionValue":"Bank_Account_Number","optionText":"Bank Account Number","selected":false},{"optionValue":"Bank_Security_Number","optionText":"Bank Security Number","selected":false},{"optionValue":"Cusip","optionText":"Cusip","selected":false},{"optionValue":"Transaction_Description","optionText":"Description","selected":false}];
      deferred.resolve(dropdownValues);
      return deferred.promise;
    }

    return {
      getDropdownValues: _getDropdownValues
    }
  }
]);

//script.js
var app = angular.module("app", []);

app.controller("homeCtrl", function($scope, homeService) {

  $scope.otherCriteria = {
    optionValue: "Bank_Account_Number",
    optionText: "Bank Account Number",
    selected: false
  };

  homeService.getDropdownValues()
    .then(function(dropdownValues) {
      $scope.criteria = dropdownValues;
    })
});

1 个答案:

答案 0 :(得分:4)

试试这个plunker

通过集合的索引引用默认值总是更好的主意(但是你想要引用它)

 $scope.criteria = dropdownValues;
 $scope.otherCriteria = $scope.criteria[0];

您可以找到更多信息here

基本上:Angular.JS使用本机JavaScript比较来比较对象。在与Angular.JS或其他任何东西无关的JavaScript中,比较对象(对象文字)是“通过引用”,因此它不会考虑对象的相似性。仅检查比较的两个引用是否指向内存中的同一对象

相关问题