对于此示例,您实际上并不需要明确的promise. $http已经返回了一个承诺,所以你真的不需要定义一个新的。
我重新安排了代码。为了初始化该值,我使用ng-init来调用该getUser()方法。然后调用$http并绑定到$scope.myUser. 顺便说一句,我注意到只进入error回调。
因为 Promise 是异步的,所以你必须绑定到$scope内部的successorerror回调函数$http。
它恢复到“旧”值的原因是因为您直接绑定到 function getUser()。这意味着 angular 正在$watch为此函数的返回值设置 a 。
这是一个工作小提琴。
HTML:
<h4>remote</h4>
<div ng-app="app" ng-controller="Ctrl" ng-init="init()">
<a href="#" editable-text="myUser.name" >
{{ myUser.name || 'not set!' }}
</a>
</div>
JS:
app.controller('Ctrl', function($scope, $http, $q) {
$scope.myUser = null;
$scope.init = function() {
getUser();
};
function getUser() {
return $http({
url : 'http://espn.com/images/test-data/public-profile.json',
method : 'GET',
})
.error(function(data) {
$scope.myUser = {"name":"bobby","age":"21"};
})
.success(function(data) {
console.log(data);
$scope.myUser = data;
});
};
});