Javascript AngularJS:模型值更改时更新选择视图
我的Javascript AngularJS:模型值更改时更新选择视图,javascript,angularjs,Javascript,Angularjs,我的select看起来像 <select data-ng-model="transaction.category" class="form-control" data-ng-options="category.name group by category.parent for category in categories" required> </select> angular.mod
select
看起来像
<select data-ng-model="transaction.category"
class="form-control"
data-ng-options="category.name group by category.parent for category in categories"
required>
</select>
angular.module('transactionService', ['ngResource']).factory('Transaction', function ($resource) {
return $resource('/user/transactions/:transactionId',
{transactionId: '@uuid'},
{
getRecent: {method: 'GET', params: {recent: true}, isArray: true},
getForYearMonth: {method: 'GET', params: {}, isArray: true}
});
});
我设置的值如下
var transaction = new Transaction();
transaction.name = $scope.transaction.name;
transaction.category = $scope.transaction.category.uuid;
类别
看起来像
[ {
name: Alcohol & Bars
parent: Food & Drink
uri: /categories/9b1e97f2-ac7d-4caf-85fc-476cd97dd6cb
uuid: 9b1e97f2-ac7d-4caf-85fc-476cd97dd6cb
} , {
name: Coffee & Tea
parent: Food & Drink
uri: /categories/cf040e77-2faa-41de-b9f7-3749a42735ac
uuid: cf040e77-2faa-41de-b9f7-3749a42735ac
} ...
]
当我从下拉列表中选择值时,一切正常
那么问题出在哪里?在某些情况下,我希望根据一些预先填充的用户偏好设置
类别
那我该怎么办?我做以下几点
$scope.templateSelected = undefined;
$scope.$watch('templateSelected', function () {
if ($scope.templateSelected !== undefined) {
$scope.transaction.category = $scope.templateSelected.category;
}
}, true);
我希望HTML
select元素上的值会被选中。但事实并非如此
问题?如何根据
$scope.templateSelected.category
更新我的选择选项
更新事务
如下所示
<select data-ng-model="transaction.category"
class="form-control"
data-ng-options="category.name group by category.parent for category in categories"
required>
</select>
angular.module('transactionService', ['ngResource']).factory('Transaction', function ($resource) {
return $resource('/user/transactions/:transactionId',
{transactionId: '@uuid'},
{
getRecent: {method: 'GET', params: {recent: true}, isArray: true},
getForYearMonth: {method: 'GET', params: {}, isArray: true}
});
});
默认情况下,角度跟踪基于对象参考的
中的选定值
设置$scope.transaction.category=$scope.templateSelected.category时代码>,$scope.transaction.category
不是列表中的对象
您可以要求angular根据属性使用按类别跟踪来识别所选值。uuid
:
data-ng-options="category.name group by category.parent for category in categories track by category.uuid"
请按我的需要添加该交易类别的代码。非常感谢你!