如下所示,如果$scope.equipments=...那一段,放在$.post里就不能绑定到$scope.equipments上,如果放在外面就可以,这是为什么?
mainApp.controller('equipmentsController', function($scope, $http) {
$.post("getAllDeviceList.action",
{},
function(response){
$scope.equipments = [ {
"id" : "1",
"name" : "equipment01 ",
"number" : "11"
}, {
"id" : "2",
"name" : "equipment02 ",
"number" : "22"
}, {
"id" : "3",
"name" : "equipment03 ",
"number" : "33"
} ];
}
);
$scope.equipments = [ {
"id" : "1",
"name" : "equipment01 ",
"number" : "11"
}, {
"id" : "2",
"name" : "equipment02 ",
"number" : "22"
}, {
"id" : "3",
"name" : "equipment03 ",
"number" : "33"
} ];
}
经过@lee1994522 的提醒,意识到如果用了$.post方法,那么脱离了angular的上下文,所以无法绑定到angular的$scope里。
`this is the point,pls.. $.post is not an Angular issue and the stuff
it wraps is not in an Angular world,so it's obviously that the
equipments outside is in Angular's world and it works as you expect
try $scope.$apply() when you call a "none Angular" issue if you wanna
refresh sth`
解决办法有两个:
$.post
第一个诚如@lee1994522所说,直接在$.post的回调函数的最后加上一句$scope.$apply(),把改变同步绑定到视图上
$.post("xxx.action",
{},
function(response){
if(response.result == "success"){
...
}
$scope.equipments = equipments;
$scope.$apply();
}
},
"json"
);
$http.post
AngularJS - Any way for $http.post to send request parameters instead of JSON
全局里定义:
var app = angular.module('myApp');
app.config(function ($httpProvider) {
$httpProvider.defaults.transformRequest = function(data){
if (data === undefined) {
return data;
}
return $.param(data);
}
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
然后控制器里面写:
$http.post("xxx.action").success(function(response) {
...
$scope.equipments = equipments;
});
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。