在这个例子中,你并不需要明确的promise
。 $http
已经返回一个承诺,所以你真的不需要定义一个新的承诺。
我已经重新安排了一些代码。为了初始化该值,我使用ng-init
来调用getUser()
方法。这然后调用$http
并绑定到$scope.myUser
。顺便说一句,我注意到,只有在进入error
回调。
因为承诺是异步的,所以您必须绑定到success
或error
回调函数$http
内的$scope
。
它恢复到“旧”值的原因是因为您直接绑定到函数getUser()
。这意味着角度设置了一个$watch
这个函数的返回值。
这是working fiddle。
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;
});
};
});
没准是为'$ http'使用的服务在这种情况下返回一个承诺有一定道理....能只需返回'$ http' – charlietfl
@charlietfl好的,我会更新。顺便说一句,我感到有点惊讶,解决的价值观通过这一观点。角度自动解开承诺吗? –
已经阅读过文档...虽然仍然让我感到困惑。如果它显示在页面中,会假设它已经是可编辑的对象 – charlietfl