问问题
7545 次
3 回答
3
对于简单的类型,您只需设置$scope.referral.organization
它就会神奇地工作:
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c for c in organizations">
</select>
</div>
-
function MyCtrl($scope) {
$scope.organizations = ['a', 'b', 'c', 'd', 'e'];
$scope.referral = {
organization: 'c'
};
}
如果你使用对象,它会变得更棘手,因为 Angular 似乎不够聪明,无法知道新对象实际上是相同的。除非有一些Angular hack,否则我看到的唯一方法是$scope.referral.organization
在从服务器加载后进行更新并将其分配给$scope.organizations
如下值:
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c.name for c in organizations"></select>
{{referral}}
<button ng-click="loadReferral()">load referral</button>
</div>
-
function MyCtrl($scope) {
$scope.organizations = [{name:'a'}, {name:'b'}, {name:'c'}, {name:'d'}, {name:'e'}];
$scope.referral = {
organization: $scope.organizations[2]
};
$scope.loadReferral = function () {
$scope.referral = {
other: 'parts',
of: 'referral',
organization: {name:'b'}
};
// look up the correct value
angular.forEach($scope.organizations, function(value, key) {
if ($scope.organizations[key].name === value.name) {
$scope.referral.organization = $scope.organizations[key];
return false;
}
});
};
}
于 2013-04-18T21:22:44.657 回答
0
您可以分配referral.organization
给从 ajax 获得的对象之一:
$scope.referral.organization = $scope.organizations[0]
我在plunker创建了简单的演示。按钮单击处理程序更改对象列表并选择默认对象。
$scope.changeModel = function() {
$scope.listOfObjects = [{id: 4, name: "miss1"},
{id: 5, name: "miss2"},
{id: 6, name: "miss3"}];
$scope.selectedItem = $scope.listOfObjects[1];
};
于 2014-01-08T08:55:07.793 回答
0
其他答案是正确的,因为它通常“有效”。问题最终是organization
存储在内部的键(整数)$scope.organizations
与存储在$http
响应中的键不匹配,响应存储在 JSON 中,因此作为字符串存储。Angular 没有将字符串与整数匹配。正如我在对原始问题的编辑中提到的,当时的解决方案是将$http
响应数据转换为字符串。我不确定当前版本的 Angular.js 是否仍然如此。
于 2014-01-09T02:44:26.020 回答