Tôi là người mới phát triển và tôi đã viết ứng dụng đơn giản này, nhưng không hiểu cách tôi có thể cập nhật chế độ xem, sau khi mô hình được tải từ yêu cầu ajax khi khởi động!Cập nhật AngularJS Xem sau khi Mô hình được tải từ Ajax
Mã này không hoạt động khi tôi thêm độ trễ vào photos.php, sử dụng: ngủ (3); để mô phỏng trễ máy chủ từ xa! thay vào đó nếu search.php nhanh thì nó hoạt động !!
<!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>
sản lượng 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"}]
ảnh 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, Hoãn giải pháp:
.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;
})
EDIT 2, giải pháp dịch vụ:
...
//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();
})
...
Tôi đã thêm chế độ xem .. xem chỉnh sửa của tôi. Tôi chỉ liên kết $ scope.photos = ảnh; Nhưng nếu tôi chỉnh sửa ảnh ... chế độ xem không thay đổi – StefanoCudini
Tôi nghi ngờ rằng bạn không đăng ký bộ điều khiển với Angular. photoAppModule.controller ('listCtrl', function ($ scope) {}); thay vì chỉ là một chức năng thông thường. Điều đó có thể hiệu quả. – Ketan
có lẽ :) nhưng tôi không hiểu cách đăng ký bộ điều khiển – StefanoCudini