我有复选框列表,希望从服务器返回一些选定的统计信息。
查看
<div ng-app="app" ng-controller="Ctrl">
<input ng-model="regionId">
{{getStatistic()}}
</div>
Controller
angular.module('app', [])
.controller('Ctrl', function($scope, $http) {
$scope.regionId = 'abc';
$scope.getStatistic = function() {
$http.get('serviceUrl', {params:$scope.regionId}).success(
function(data){
return data;
});
//How return data to view?
}
});
如何在 Controller 中声明函数 getStatistic()。该函数必须请求 Web 服务并在每次更改模型后返回一个字符串。
最好, 叶夫根尼。
最佳答案
当值更改时,您想要调用 Web 服务来获取结果。
$scope.toggle = function(region) {
$http.get('service/resulturl')
.success(function(result) {
$scope.statistic = result;
});
};
如您所见,Web 服务调用的结果存储在 $scope.statistic 中。这就是您需要在 View 中绑定(bind)的全部内容:
SUMMARY: {{statistic}}
编辑:
您可以 watch 而不是依赖 onChange 事件您的更改模型:
$scope.$watch('regionId', function() {
$http.get('service/resulturl')
.success(function(result) {
$scope.statistic = result;
});
});
如果您想监视值数组,请将第三个参数 true
传递给 $watch 函数以进行值比较而不是引用比较。
进一步编辑:
已看过您修改后的示例。您不希望将 GetStatistic() 调用放入 View 中,因为这会触发每个周期的 http get,这是完全不必要的。您应该绑定(bind)到您正在观察的值发生变化时设置的值,并且仅在值发生变化时触发 http get。
关于ajax - 绑定(bind)到函数,从 $http.get 获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20629502/