gpt4 book ai didi

ajax - 从Ajax加载模型后,AngularJS更新 View

转载 作者:行者123 更新时间:2023-12-04 03:44:38 26 4
gpt4 key购买 nike

我是angularjs开发的新手,我写了这个简单的应用程序,但是在启动时从ajax请求加载模型il之后,我不明白如何更新 View !

当我使用以下命令将延迟添加到photos.php中时,此代码不起作用:
sleep (3);
用于模拟远程服务器延迟!相反,如果search.php快速运行,那么它就可以了!

<!doctype html>
<html ng-app="photoApp">
<head>
<title>Photo Gallery</title>
</head>
<body>
<div ng-view></div>

<script src="../angular.min.js"></script>
<script>
'use strict';

var photos = []; //model

var photoAppModule = angular.module('photoApp', []);

photoAppModule.config(function($routeProvider) {
$routeProvider.when('/photos', {
templateUrl: 'photo-list.html',
controller: 'listCtrl' });
$routeProvider.otherwise({redirectTo: '/photos'});
})
.run(function($http) {
$http.get('photos.php')//load model with delay
.success(function(json) {

photos = json; ///THE PROBLEM HERE!! if photos.php is slow DON'T update the view!

});
})
.controller('listCtrl', function($scope) {

$scope.photos = photos;

});
</script>
</body>
</html>

photos.php的输出
[{"file": "cat.jpg", "description": "my cat in my house"},
{"file": "house.jpg", "description": "my house"},
{"file": "sky.jpg", "description": "sky over my house"}]

photo-list.html
<ul>
<li ng-repeat="photo in photos ">
<a href="#/photos/{{ $index }}">
<img ng-src="images/thumb/{{photo.file}}" alt="{{photo.description}}" />
</a>
</li>
</ul>

编辑1,推迟解决方案:
.run(function($http, $q) {

var deferred = $q.defer();

$http.get('photos.php')//load model with delay
.success(function(json) {
console.log(json);

photos = json; ///THE PROBLEM!! if photos.php is slow DON'T update the view!

deferred.resolve(json);//THE SOLUTION!
});

photos = deferred.promise;
})

编辑2,服务解决方案:
... 
//require angular-resource.min.js
angular.module('photoApp.service', ['ngResource']).factory('photoList', function($resource) {
var Res = $resource('photos.php', {},
{
query: {method:'GET', params:{}, isArray:true}
});
return Res;
});

var photoAppModule = angular.module('photoApp', ['photoApp.service']);

...

.run(function($http, photoList) {

photos = photoList.query();
})
...

最佳答案

简短的答案是这样的:

.controller('listCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$timeout(function () {
$scope.photos = photos;
}, 0);
}]);

长答案是:请不要像这样混合常规javascript和angular。重新编写代码,以便angular随时知道发生了什么。
var photoAppModule = angular.module('photoApp', []);

photoAppModule.config(function($routeProvider) {
$routeProvider.when('/photos', {
templateUrl: 'photo-list.html',
controller: 'listCtrl'
});

$routeProvider.otherwise({redirectTo: '/photos'});
});

photoAppModule.controller('listCtrl', ['$scope', function($scope) {
$scope.photos = {};

$http.get('photos.php') // load model with delay
.success(function(json) {
$scope.photos = json; // No more problems
});
}]);

关于ajax - 从Ajax加载模型后,AngularJS更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com