如何从db + angular js中显示所选选项的静态

时间:2017-11-16 13:50:41

标签: php angularjs

<select name="gender" ng-model="list.gender" data-select-id="bc813756-82d5-45d7-932c-ab9afd0a08da" class="initialized">
    <option value="" disabled="">Gender</option>
    <option ng-selected="list.gender == 'Male'" value="Male" >Male</option>
    <option ng-selected="list.gender == 'Female'" value="Female" >Female</option>                 
</select>

假设我从DB获取"Male"值,如何显示所选选项?

2 个答案:

答案 0 :(得分:0)

在你的情况下,就像你只有两种选择(男性或女性)可以使用真或假:

&#13;
&#13;
var app = angular.module('GenreApp', []);

app.controller('MainCtrl', function($scope) {
  // This would be the value get from your DB
  var genreGetFromDB = 'female';
  
  // Here you validate the value of the genre
  if (genreGetFromDB != 'male') {
    $scope.genre = false;
  } else {
    $scope.genre = true;
  }
});
&#13;
<!DOCTYPE html>
<html ng-app="GenreApp">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <select aria-label="ngSelected demo">
      <option>Female</option>
      <option ng-selected="genre">Male</option>
    </select>
  </body>

</html>
&#13;
&#13;
&#13;

继续摇滚!

答案 1 :(得分:0)

我们不应该同时使用ng-modelng-selected。这就是AngularJS文档所说的内容:

  

注意: ngSelected不与selectngModel指令互动,它只在元素上设置selected属性。如果您在选择中使用ngModel,则不应在选项上使用ngSelected,因为ngModel会设置选择值和所选选项。

因此,从选项中删除ng-selected指令,并将控制器中的list.gender设置为从数据库中提取的值。

app.controller('someController', ['$scope', function($scope){
    // .... some code ...
    $scope.list = { gender: 'Male' }; // set this to the value from DB

    // .... some code ...
}]);

HTML

<select name="gender" ng-model="list.gender" class="initialized">
    <option value="" disabled="">Gender</option>
    <option value="Male" >Male</option>
    <option value="Female" >Female</option>
</select>

希望有所帮助