为什么视图没有更新为"某人"?
var app = angular.module('Async', []);
app
.controller('MainController', function($scope) {
$scope.user = {
name: "No one"
};
jQuery.ajax("/"
, {
async: true,
type: "POST",
}
).always(function() {
$scope.user.name = "Someone";
alert($scope.user.name);
});
});
angular.bootstrap(document, ['Async']);Run Code Online (Sandbox Code Playgroud)
<div data-ng-controller="MainController">
<div data-ng-view="">User's name: {{ user.name }}</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-route.js"></script>Run Code Online (Sandbox Code Playgroud)
当您在角度世界之外进行此类异步调用时,您需要通知角度您所做的任何更改.有几种方法可以解决此问题:
第一个选项:在你的回调中运行$ scope.$ apply()来告知angular你正在改变的事情:
jQuery.ajax("/"
, {
async: true,
type: "POST",
}
).always(function() {
$scope.apply(function() {
$scope.user.name = "Someone";
alert($scope.user.name);
})
});
Run Code Online (Sandbox Code Playgroud)
第二个选项(首选):jQuery.ajax使用angular的内置替换调用$http,这将为您处理$ apply步骤:
app
.controller('MainController', function($scope, $http) {
$scope.user = {
name: "No one"
};
$http({
method: 'POST',
url: '/'
}, function(successResponse) {
$scope.user.name = successResponse.data.name;
alert($scope.user.name);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4858 次 |
| 最近记录: |