获取要在 ng 选项中显示的数据,但设置动态默认值



用户对象可用于填充表单的视图。显示信息的元素之一是下拉列表。提出了两个请求。一个用于user information,另一个用于timezones列表。两者都通过如下所示的ui-router状态进行解析:

.state('app.userprofile', {
url: '/userprofile',
component: 'user',
resolve: {
user: ['userService', function(userService) {
return userService.fetchUser();
}],
timezones: ['timezoneService', function(timezoneService){
return timezoneService.fetchUsaTimeZones();
}]
}
})
}]);

select元素未能填充用户时区后,我阅读了我在网上找到的一篇文章,但选择元素仍然无法显示信息。

问题

如何使用来自用户的数据填充默认选择选项object但填充第二个响应中的选项。

<label for="timezones">Time Zone</label>
<div>
<select name="timezones"
ng-init="userTimezone = $ctrl.user.business.timezone"
ng-change="userTimezone = userTimezone.abbr"
ng-model="userTimezone" 
ng-options="item as item.abbr for item in $ctrl.timezones track by item.abbr" class="form-control">
<option value="">{{userTimezone}}</option>
</select>
<p>{{userTimezone}}</p>
</div>

//SECOND REQUEST FOR TIMEZONES
app.factory('timezoneService', ['$http', '$q', function($http, $q){
var factory = {};
factory.fetchUsaTimeZones = function() {
var deferred = $q.defer();
$http.get('../../p3sweb/assets/json/ustimezones.json')
.then(
function(response){
console.log(response.data.ustimezones)
deferred.resolve(response.data.ustimezones)
},
function(errResponse){
deferred.resolve(errResponse)
}
);
return deferred.promise;
}
return factory;
}])

{
"ustimezones": [
{
"value": "Hawaiian Standard Time",
"abbr": "HST",
"offset": -10,
"isdst": false,
"text": "(UTC-10:00) Hawaii",
"utc": [
"Etc/GMT+10",
"Pacific/Honolulu",
"Pacific/Johnston",
"Pacific/Rarotonga",
"Pacific/Tahiti"
]
},
{
"value": "Alaskan Standard Time",
"abbr": "AKDT",
"offset": -8,
"isdst": true,
"text": "(UTC-09:00) Alaska",
"utc": [
"America/Anchorage",
"America/Juneau",
"America/Nome",
"America/Sitka",
"America/Yakutat"
]
}
]
}

更新

当我将ng-model的值作为$ctrl.user.business.timezone时,它抛出了一个错误,所以我通过ng-init指令将其存储在变量userTimezone中。更新了代码

更新 2

我有它半工作。它会更新所有字段,尽管会引发不一致的 405 错误。不会撒谎,我处于"这到底是如何工作的"情况之一。

<select name="timezones"
ng-init="userTimezone._abbr = {abbr: $ctrl.user.business.timezone}"
ng-change="$ctrl.user.business.timezone = userTimezone._abbr"
ng-model="userTimezone._abbr" 
ng-options="zone.abbr as zone.text for zone in $ctrl.timezones track by zone.abbr" class="form-control">
<option value="">{{userTimezone._abbr}}</option>
</select>
<p>{{userTimezone._abbr}}</p>

你有复杂的对象作为你的选项。Angular 在检查默认值(通过ng-model属性设置(时会进行相等比较,因此对于对象,它会比较对象引用(通过生成的$$hashkey属性(。因为您有两个不同的对象引用,一个来自时区列表,一个来自用户,所以它们的哈希键是不同的。因此,它们被视为"不相等",因此不会设置默认值。

如果扩展ng-options属性以使用track by,则可以选择相等比较更有意义的唯一基元属性(如缩写(。然后,Angular 将使用此属性进行相等/唯一性比较,而不是哈希键。

所以你会有类似的东西

<select name="timezones" ng-model="$ctrl.user.business.timezone" ng-options="item as item.abbr for item in $ctrl.timezones track by item.abbr"></select>

最新更新