我想通过一个服务将对象分配给$ scope对象。但是,我得到一个错误,说该对象是未定义的。我正在进行异步调用来获取对象,下面我使用$ timeout服务来模拟相同的。我试过$ q.defer()并返回一个承诺,怀疑它是一个计时问题,并且还调用$ apply()来调用绑定,但似乎没有任何工作。以下是链接到plunker中的代码。请帮我解决这个问题。 http://plnkr.co/edit/wyF4Bx1a39IEWS3m8Loe?p=info
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="profctrl">
<p>Hello {{usr}}!</p>
</body>
</html>
var ub = angular.module('app', []);
ub.controller('profctrl', ["$scope", "formsub", "$log", "$timeout", function($scope, formsub, $log, $timeout) {
$log.log("In Profile controller");
$scope.msg = "";
$scope.usr = {};
var fbresponse = {
name: 'xyz',
email: '[email protected]'
};
$scope.usr = formsub.getprof(fbresponse);
$timeout(function() {
$log.log('$scope.usr', $scope.usr);
}, 2000);
}]);
ub.service('formsub', ["$http", "$log", "$q", "$timeout", function($http, $log, $q, $timeout) {
var user = {};
var self = this;
self.msg = "";
self.getprof = function(user) {
$timeout(function() {
$log.log('user assigned');
return user;
}, 2000);
} //getprof
}]);
的可能的复制[我如何返回a的回复同步调用?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –
它确定..解决了吗? –