简体   繁体   English

如何设置选项角度的默认值

[英]How can I set default value for option angular

I have select like this 我有这样的选择

<select  ng-model="form.data">
    <option  value="c" ng-repeat="c in data">{{c}}</option>     
</select>

$scope.data= response.data

When I change select and click save . 当我更改时,选择并单击保存。 It save successful in database . 成功保存到数据库中。 I want when refresh page . 我想要刷新页面时。 select show value I save in database. 选择我保存在数据库中的显示值。 How can I do this . 我怎样才能做到这一点 。 Please help me 请帮我

The best way would be using the ng-options directive: 最好的方法是使用ng-options指令:

<select ng-model="form.data" ng-options="c for c in data"></select>

This way, when refreshing your page the select will be default set to the value of $scope.form.data , as expected. 这样,刷新页面时,选择将默认设置为$scope.form.data的值,如预期的那样。

Use ng-selected 使用ng-selected

<select ng-model="form.data">
  <option value="c" ng-repeat="c in data" ng-selected="c == form.data">{{c}}</option>
</select>

For people who are searching for a answer in Angular | 对于在Angular中寻找答案的人| angular 2 | 角2 | angular 4 角度4

try using NgValue and make sure your default options value is the model so NgValue="ModelName" 尝试使用NgValue并确保您的默认选项值为模型,因此NgValue="ModelName"

    <select  ng-model="form.data">
      <option  NgValue="form.data">yourdefaultoption</option>
      <option  NgValue="c" ng-repeat="c in data">{{c}}</option>
    </select>

Some advice : 一些忠告 :

  • Use ng-options directive instead of traditional option element. 使用ng-options指令代替传统的option元素。
  • To display the previous selected value on page refresh use HTML5 localStorage or sessionStorage . 要在页面刷新时显示先前选择的值,请使用HTML5 localStoragesessionStorage

Working Demo 工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM