为什么在运行时没有可用的变量$ scope.reserved?在模板中{{reserved}}是ок,但在控制器值= undefibed。
我有以下代码
服务
'use sctict'
angular.module('starter.services', [])
.service('api', ['$http', '$q', function api($http, $q) {
var server = 'http://localhost/ires-api';
var jsondata = {
getReservedHours: function (masters, date) {
var deferred = $q.defer();
var promise = $http({ method: 'GET', url: server + '/reservations/' + masters + '/' + date, cache:true})
.success(function(response) {
//return response;
deferred.resolve({
data: response
});
}).error(function(msg, code) {
deferred.reject(msg);
$log.error(msg, code);
});
return deferred.promise;
},
}
return jsondata;
}]);
控制器
$scope.click = function(){
masters = [5,51];
api.getReservedHours(masters, '2007/08/27').then(function(response) {
$scope.reserved = response.data;
});
console.log($scope.reserved); // undefined ....
}
答案 0 :(得分:0)
我认为你错过了作业?
api.getReservedHours(masters, '2007/08/27').then(function(response) {
$scope.reserved = response.data;
});
答案 1 :(得分:0)
因为" getReservedHours"是一个异步请求,并且打印时$ scope.reserved未定义(因为请求未完成)。请改用此代码
$scope.click = function(){
masters = [5,51];
api.getReservedHours(masters, '2007/08/27').then(function(response) {
$scope.reserved = response.data;
console.log($scope.reserved); // This would work
});
console.log($scope.reserved); // undefined ....
}