使用AngularJS中的$http服务来获取数据的时候就在想,如果使用jQuery的封装的ajax方法来获取数据是否可行。
第一次的时候是按照如下样子写的:
angular.module('myApp',[]).controller('myController',function($scope,$http){
// $http.get('JSON对象数据.json').then(function(response) {
// $scope.persons = response.data.person;
// console.log(response.data.person);
// });
$.ajax({
type:"get",
url:"JSON对象数据.json",
dataType:"json",
async:true,
success:function(response) {
$scope.persons = response.person;
}
});
});
然后就发现$scope.persons的值确实是放进去了,但是在页面中却没有显示出来。
在百度中查找的时候才知道是因为Angular的双向绑定在和第三方类库混用的时候会失效,所以还要在最后使用$scope.$apply();再进行一次绑定。
实际有效代码如下:
angular.module('myApp',[]).controller('myController',function($scope,$http){
// $http.get('JSON对象数据.json').then(function(response) {
// $scope.persons = response.data.person;
// console.log(response.data.person);
// });
$.ajax({
type:"get",
url:"JSON对象数据.json",
dataType:"json",
async:true,
success:function(response) {
$scope.persons = response.person;
$scope.$apply();
}
});
});