绑定NG选项远程JSON数据? [英] Bind ng-options to remote JSON data?
问题描述
使用AngularJS,我想选择选项绑定到远程数据源,而跳过了中间领域的需要。我不知道这是可能的。
Using AngularJS, I'd like to bind select options to a remote data source while skipping the need for an intermediate field. I'm not sure this is possible.
例如,我理想中的HTML是:
For example, my ideal HTML would be:
<select ng-model="city" ng-options="obj for obj in getCities(state).data"></select>
我的范围的getCities调用需要的状态值(型号其他约束),并使用$ http.get获得城市名单进行远程调用。
The call to my scope's getCities takes the state value (bound elsewhere on the model) and makes a remote call using $http.get to get the list of cities.
在我的情况下,将有由同一控制器管理多个选择并因此存在不存储每个组返回的数据的一个单一的地方,也没有我想知道什么时候来执行查询。
In my scenario, there would be multiple selects managed by the same controller and thus there isn't a single place to store each set of data returned, nor would I know exactly when to perform the query.
我在寻找如何做到这一点的建议。我不能只是返回从getCities的$ HTTP的承诺,因为它是那么反复调用。
I'm looking for suggestions on how to do this. I can't just return an $http promise from getCities because it is then called repeatedly.
推荐答案
我误解究竟你是在我的评论上述要求。你可以用一种后期绑定方法把这事办成。你的 ngOption
应该看你的模型为正常,和你的承诺回调应该修改控制器的范围。
I misunderstood what exactly you were asking in my comment above. You can pull this off with a sort of late-binding approach. Your ngOption
should be looking at your model as normal, and your promise callback should modify your controller's scope.
小提琴: http://jsfiddle.net/XaC8e/1/
HTML
<div ng-app="test" ng-controller="test">
<select ng-model="state1" ng-options="s for s in states" ng-change="loadNewCities(state1);">
</select>
<br/>
<select ng-model="city1" ng-options="c for c in cities[state1]">
</select>
<br/>
<br/>
<select ng-model="state2" ng-options="s for s in states" ng-change="loadNewCities(state2);">
</select>
<br/>
<select ng-model="city2" ng-options="c for c in cities[state2]">
</select>
<br/>
<br/>
<select ng-model="state3" ng-options="s for s in states" ng-change="loadNewCities(state3);">
</select>
<br/>
<select ng-model="city3" ng-options="c for c in cities[state3]">
</select>
<br/>
<br/>
1: {{city1}}, {{state1}}
<br/>
2: {{city2}}, {{state2}}
<br/>
3: {{city3}}, {{state3}}
</div>
JavaScript的:
JavaScript:
angular.module('test', [])
.controller('test', function ($scope) {
$scope.states = ['ca', 'ny', 'va'];
$scope.cities = {
'ca': ['san diego', 'san francisco']
};
$scope.loadNewCities = function (s) {
if (typeof $scope.cities[s] !== 'undefined') {
// don't load if we already have cities
return;
}
// TODO call a service here, run the $scope.$apply in the callback
if (s == 'ny') {
setTimeout(function () {
// faking a callback
$scope.$apply(function () {
$scope.cities[s] = ['nyc', 'buffalo'];
});
}, 200);
}
if (s == 'va') {
setTimeout(function () {
// faking a callback
$scope.$apply(function () {
$scope.cities[s] = ['richmond', 'chesapeake'];
});
}, 200);
}
};
});
这篇关于绑定NG选项远程JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!