做angularJs相关项目时,发现绑定在页面上的数据渲染有问题,部分代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
routingDemoApp.controller('CloudService', ['$scope', '$http', '$location', function ($scope, $http, $location) {
//加载项目列表
$http({
method: 'post',
url: '/api/getlist',
data: { token: token, data1: val1 }
}).then(function (json) {
var json = json.data;
$scope.pnamedata = json.data;
......

}, function (json) {
//失败时执行
...
});

$.post("/api/getlist", { token: token, data1: val1 }, function (json) {
$scope.pnamedata = json.data;
......

$scope.$apply();
})

$scope.addCloudUser = function () {
$("#addUserModal").modal('show');
};

}])

当页面触发addCloudUser函数时,页面数据$scope.pnamedata才会渲染,并不是页面加载时渲染数据。我们先排除页面路由的控制器配置是否正确,页面控制器是否注入$scope等依赖部件。

通过搜罗发现,是AngularJs的$http和jquery的ajax混用导致,在AngularJS中使用了ajax请求数据时,AngularJS是监听不到的,解决办法有两种:一是通过$scope.$apply();强制渲染一下;
二是使用AngularJs自带的http模块$http,用法和jquery的ajax差不多,具体代码如上。