简体   繁体   English

Angular.js默认选择所选值

[英]Angularjs Default Select Selected Value

I generate a table using ng-repeat that loops over user submitted data. 我使用ng-repeat生成了一个表,该表循环了用户提交的数据。 Inside of the ng-repeat I have a field, a select, that I use another ng-repeat to build a list of types. 在ng-repeat内部,我有一个选择字段,我使用另一个ng-repeat来建立类型列表。 This too generates the appropriate select. 这也会生成适当的选择。 However, I cannot figure out how to have the select defaulted to the users's value; 但是,我无法弄清楚如何将选择默认为用户的值。 eg User selects book as the type, when the user reloads the page I want the select to have "book" preselected. 例如,用户选择书作为类型,当用户重新加载页面时,我希望选择的书具有“书”。

<tr ng-repeat="item in userData" ng-include="'templates/bookmarkrow.html'"></tr>
...
<select ng-model="item.type" ng-options="option.name for option in typeOptions track by option.value" class="form-control hidden"></select>

I thought the ng-model would bind the select to the value of item.type. 我以为ng模型会将选择绑定到item.type的值。 Any ideas? 有任何想法吗?

Additional Details 额外细节

typeOptions is an array of objects; typeOptions是一个对象数组; eg [{'name': 'some name', 'value': 'some value', ...}]. 例如[{'name':'some name','value':'some value',...}]。 As for the data, I'm aware that AngularJS doesn't store the data. 至于数据,我知道AngularJS不存储数据。 Assume in this example that data is coming from a data store; 在此示例中,假设数据来自数据存储; be it database or local storage. 无论是数据库还是本地存储。 The larger point is I will have loaded data in the client side and want to indicate it in the select. 更大的一点是,我将在客户端加载数据,并希望在选择中指示它。

Since angular does not persist data across page reloads the data will be lost when a full reload occurs. 由于angular不会在整个页面重新加载过程中保留数据,因此当完全重新加载时,数据将丢失。 If you are using angular routes or ui-router then you can persist data in factories which are singletons. 如果您使用角度路由或ui-router,则可以将数据持久保存在单例工厂中。

To save data across page reloads you can (as mentioned) use local storage, cookies or store it the in the backend of your application. 要保存跨页面重新加载的数据,您可以(如上所述)使用本地存储,cookie或将其存储在应用程序的后端。

To just initialize a value you can use ng-init 要只初始化一个值,可以使用ng-init

I rewrote my code to use ng-repeat on the option, instead of using ng-options on the select. 我将代码重写为在选项上使用ng-repeat,而不是在select上使用ng-options。 After that I used ng-selected on the option to decide which option is selected. 之后,我在选项上使用了ng-selected来决定选择哪个选项。

<select class="form-control hidden">
    <option selected-value="{{option.value}}" ng-selected="{{item.type == option.value}}" ng-repeat="option in typeOptions">{{option.name}}</option>
</select>

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

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