如何根据angularJS中的数据将'selected'放入html选项中?

时间:2016-05-17 09:42:08

标签: javascript php angularjs

我正在开发一个angularJS。这是我在PHP中的代码:

<label class="item item-input item-select">
    <div class="input-label">Do you have the right to work in UK?</div>
    <select name="do_you_have_the_right_to_work_in_uk" ng-model="do_you_have_the_right_to_work_in_uk">
        <option value="">Select</option>
        <option value="yes" <?php echo $user->do_you_have_the_right_to_work_in_uk == 'yes' ? 'selected' : ''; ?>>Yes</option>
        <option value="no" <?php echo $user->do_you_have_the_right_to_work_in_uk == 'no' ? 'selected' : ''; ?>>No</option>
    </select>
</label>

考虑变量{{user_data.do_you_have_the_right_to_work_in_uk}}保持'是'或'否'。在angularJS中我的PHP代码的等价是什么?

3 个答案:

答案 0 :(得分:1)

Actualy您不需要在选项选择中添加条件。相反,只设置ng-model="do_you_have_the_right_to_work_in_uk"应该起作用

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

app.controller('MainCtrl', function($scope) {
  $scope.do_you_have_the_right_to_work_in_uk =  "no"
});
  <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>


<body ng-app="myApp" ng-controller="MainCtrl">
  <label class="item item-input item-select">
    <div class="input-label">Do you have the right to work in UK?</div>
    <select name="do_you_have_the_right_to_work_in_uk" ng-model="do_you_have_the_right_to_work_in_uk">
      <option value="">Select</option>
      <option value="yes">Yes</option>
      <option value="no" >No</option>
    </select>
  </label>
</body>

</html>

答案 1 :(得分:0)

已选择仅使用已选择=&#34;已选择&#34; 。这会将所选属性添加到选项中。

<option value="yes" <?php echo $user->do_you_have_the_right_to_work_in_uk == 'yes' ? 'selected="selected"' : ''; ?>>Yes</option>

答案 2 :(得分:0)

使用ng-selected

<select name="do_you_have_the_right_to_work_in_uk" ng-model="do_you_have_the_right_to_work_in_uk">
  <option value="">Select</option>
  <option value="yes" ng-selected="do_you_have_the_right_to_work_in_uk === 'yes'">Yes</option>
  <option value="no" ng-selected="do_you_have_the_right_to_work_in_uk === 'no'">No</option>
</select>