AngularJS从Ajax加载模型后更新视图

10

我是angularjs开发的新手,写了这个简单的应用程序,但不知道如何在模型从ajax请求中加载后更新视图!

当我在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();
})
...
4个回答

6
简短回答如下:
.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
        });
}]);

4

1

是的,它可以工作,但我不知道它是否是在angularjs中通常使用的最佳解决方案。 请查看我的EDIT 2,这是使用服务的第二种解决方案,我只想知道服务是否以这种方式定义得很好。 你认为哪一个更优雅?? 谢谢! - stefcud
1
在我看来,服务是最好的选择。首先,它可以在所有控制器中重复使用。 - user554180
谢谢!是的,我只是在其他讨论中验证它。 - stefcud

0
你需要将视图中的元素绑定到你的$scope对象的属性(简单或对象)上。一旦$scope对象被更新,视图应该自动更新。这就是AngularJS的美妙之处。
编辑: 请将你的控制器注册为
photoAppModule.controller('listCtrl', function($scope){
  $scope.photos = photos;

});

如果“photos”变量不可用,则可能需要创建一个带有该变量并将其注入到控制器中的服务。

我已经添加了视图,请查看我的编辑。但是,如果我编辑照片... 视图不会改变。我只是绑定了 $scope.photos = photos; - stefcud
我怀疑你没有在Angular中注册控制器。尝试使用以下代码:photoAppModule.controller('listCtrl', function($scope){});而不是普通函数。这可能有效。 - Ketan
也许 :) 但我不明白如何注册控制器。 - stefcud
我正在重写所有代码,以使其更清晰。感谢您的建议!但是如果Ajax请求被延迟,它将无法工作。 - stefcud
是的,我忘记了如果控制器中的代码直接运行,即使photo中没有任何内容,也会出现竞争条件。我认为延迟应该可以解决这个问题。 - Ketan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接