异步问题
ajax异步请求数据完数据后给$scope赋值的时候需要检查$scope的数据更新没有。要不然无法绑定数据。
<!DOCTYPE html><html ng-app="test_ajax"> ?<head> ???<meta charset="utf-8"> ???<title></title> ???<script src="angular.js" charset="utf-8"></script> ???????<script src="jquery.js"></script> ???<script> ???let mod=angular.module(‘test_ajax‘, []); ???mod.controller(‘main‘, function ($scope){ ?????$.ajax({ ???????url: ‘arr.txt‘, ???????dataType: ‘json‘, ???????success(res){ ?????????$scope.arr=res; ?????????$scope.$apply(); //检查 ???????}, ???????error(){ ?????????alert(‘错了‘); ???????} ?????}); ???}); ???</script> ?</head> ?<body ng-controller="main"> ???<ul> ?????<li ng-repeat="a in arr">{{a}}</li> ???</ul> ?</body></html>
$scope.$apply(); //检查
直接用angularjs方法get方法请求数据
<!DOCTYPE html><html ng-app="test_ajax"> ?<head> ???<meta charset="utf-8"> ???<title></title> ???<script src="angular.js" charset="utf-8"></script> ???<script> ???let mod=angular.module(‘test_ajax‘, []); ???mod.controller(‘main‘, function ($scope, $http){ ?????$http.get(‘arr.txt‘).then((res)=>{ ???????$scope.arr=res.data; ?????}, (err)=>{ ???????alert(‘错了‘); ?????}); ???}); ???</script> ?</head> ?<body ng-controller="main"> ???<ul> ?????<li ng-repeat="a in arr">{{a}}</li> ???</ul> ?</body></html>
angularjs数据交互
原文地址:https://www.cnblogs.com/tianranhui/p/9333530.html