我是angularjs開發人員的新手,我寫了這個簡單的應用程序,但不明白我是如何更新視圖,在啓動後從ajax請求加載模型!AngularJS更新從Ajax加載模型後查看
當我向photos.php中添加延遲時,此代碼不起作用: sleep(3);用於模擬遠程服務器延遲的 !相反,如果search.php是快速的工作!
.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;
})
:
<!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"}]
光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>
EDIT 1,推遲溶液的輸出
EDIT 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();
})
...
我加了視圖..看我的編輯。 我只是綁定$ scope.photos = photos; 但是,如果我編輯照片...視圖不會改變 – StefanoCudini 2013-05-05 23:10:16
我懷疑你沒有註冊與Angular的控制器。 photoAppModule。控制器('listCtrl',函數($ scope){}); 而不只是一個常規功能。這可能會起作用。 – Ketan 2013-05-05 23:12:02
也許:)但我不明白如何註冊控制器 – StefanoCudini 2013-05-05 23:13:48