我正在为 $http.get 方法使用 angularjs 代码,但是当我尝试访问 $scope.metric.label 时。它给出了类似 "Error: $scope.metric is undefined
is not defined. I want to create the dynamic url from selection options. 但我无法创建动态网址。
演示 http://plnkr.co/edit/UrufgAUqjT8GOLz7QVsL?p=preview
在演示中,取消注释 alert(url) 您会看到它不起作用
//Fetching the metrics and filling the metric selection options
$http.get("https:localhost:8080/metering/data/")
.success(function(response) {
$scope.metrics = response.nova_meters.concat(response.glance_meters).concat(response.cinder_meters).concat(response.ipmi_meters).concat(response.neutron_meters).concat(response.swift_meters).concat(response.kwapi_meters);
$scope.metric = $scope.metrics[0];
});
// Fetching the list of instances and filling the Group by selection options
$http.get("https:localhost:8080/metering/project/")
.success(function(response) {
//alert(JSON.stringify(response[0].instances));
$scope.groups = response[0].instances;
$scope.group_by = $scope.groups[0];
});
var url = "localhost?" + "meter=" + $scope.metric.label + "&group_by=project" ;
console.log(url);
HTML
<div ng-controller="ceilometerCtrl">
<select ng-model="metric" ng-options="value.label group by value.group for value in metrics" ng-change="update()">
</select>
<select ng-model="group_by" ng-options="value.Id for value in groups" ng-change="update()">
</select>
</div>
最佳答案
由于您的请求是异步,您必须处理回调以检索一些数据。
在 angularJs 中,$http 返回一个 promise,因此您可以组合它们。
此外,您还可以使用 $q 服务和 .all() 方法。该方法以一组 promise 作为参数,并返回一个 promise,当参数数组中的 promise 被解析为时,该 promise 将被解析。
此外,如果您设置一个对象的属性,如$scope.metric,您必须声明它,该对象必须被定义。
Controller
(function(){
function Controller($scope, $http, $q) {
//Declare metric
$scope.metric = {};
var defer = $q.defer();
var url = '';
//Declare promise
var promise1 = $http.get("path_to_url");
var promise2 = $http.get("another_path");
//Declare our function callback to launch when promises are finished
function callback(response){
//response is an array of promises results, in the same order
//reponse[0] is the promise1 result
$scope.metric.name = response[0].data.name;
//response[1] is the promise2 result
$scope.group_by = response[1].data.group;
url = "localhost?" + "meter=" + $scope.metric.name + "&group_by=" + $scope.group_by ;
//Resolve data with the built url
defer.resolve(url);
}
//When all promise are completed, then call callback function
$q.all([promise1, promise2]).then(callback);
//Callback for our resolve result
function print(url){
console.log(url);
}
//Print data when the url is set
defer.promise.then(print);
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
关于javascript - 来自外部 $http.get 方法的 Angular : How to access angular $scope. ng-model_name?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31829653/