AngularJS : 服务在我的控制器中没有解析
AngularJS : Services are not resolved in my controller
Angularjs 控制器无法解析服务数据。
var kattaApp = angular.module('kattaApp', []).controller('kattaController', function($scope, dataFactory) {
var promise = dataFactory.getResult().then(function(data) {
return data;
console.log(data);
});
promise.then(function(data) {
$scope.message = data;
console.log(data.geonames[0].countrycode);
});
console.log(" :'( Scope is not working " + $scope.message);
});
angular.module('kattaApp').factory('dataFactory', function($http, $q) {
return {
getResult: getResult
};
function getResult() {
var deferred = $q.defer();
$http.get('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo').success(function(data, status) {
deferred.resolve(data);
}).error(function(data) {
deferred.reject(data);
});
return deferred.promise;
};
});
在上面的代码中,我试图设置 $scope.message
的值。当我调用该服务时,它返回未定义的数据,一段时间后,获取数据并在我的控制台中打印。
请看我的Plnkr Link
您看到的结果类似于
:'( Scope is not working undefined
在浏览器控制台中,因为您保留了
console.log(" :'( Scope is not working "+$scope.message);
外面然后回调把它放在里面然后回调你会得到 $scope.message
正确的值。
如果你把promise.then改成这样。
promise.then(function(data){
$scope.message = data.geonames[0].countrycode;
console.log(data.geonames[0].countrycode);
console.log("$scope.message: "+$scope.message);
});
您会收到类似
的消息
$scope.message: MX
这是更新的 plunker link
更新
从 {{scope.message}}
中删除 $scope
而是像
那样使用它
<h6>{{ message}}</h6>
你的代码中有几个错误,我让它工作了,例如<h6>{{ message }}</h6>
而不是 <h6>{{ $scope.message }}</h6>
.
希望这就是您要找的:
Angularjs 控制器无法解析服务数据。
var kattaApp = angular.module('kattaApp', []).controller('kattaController', function($scope, dataFactory) {
var promise = dataFactory.getResult().then(function(data) {
return data;
console.log(data);
});
promise.then(function(data) {
$scope.message = data;
console.log(data.geonames[0].countrycode);
});
console.log(" :'( Scope is not working " + $scope.message);
});
angular.module('kattaApp').factory('dataFactory', function($http, $q) {
return {
getResult: getResult
};
function getResult() {
var deferred = $q.defer();
$http.get('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo').success(function(data, status) {
deferred.resolve(data);
}).error(function(data) {
deferred.reject(data);
});
return deferred.promise;
};
});
在上面的代码中,我试图设置 $scope.message
的值。当我调用该服务时,它返回未定义的数据,一段时间后,获取数据并在我的控制台中打印。
请看我的Plnkr Link
您看到的结果类似于
:'( Scope is not working undefined
在浏览器控制台中,因为您保留了
console.log(" :'( Scope is not working "+$scope.message);
外面然后回调把它放在里面然后回调你会得到 $scope.message
正确的值。
如果你把promise.then改成这样。
promise.then(function(data){
$scope.message = data.geonames[0].countrycode;
console.log(data.geonames[0].countrycode);
console.log("$scope.message: "+$scope.message);
});
您会收到类似
的消息$scope.message: MX
这是更新的 plunker link
更新
从 {{scope.message}}
中删除 $scope而是像
那样使用它<h6>{{ message}}</h6>
你的代码中有几个错误,我让它工作了,例如<h6>{{ message }}</h6>
而不是 <h6>{{ $scope.message }}</h6>
.
希望这就是您要找的: