AngularJS在从Ajax加载模型后更新View

时间:2013-05-05 22:31:20

标签: ajax angularjs

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

当我在photos.php中添加延迟时,此代码不起作用,使用:     睡眠(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"}]

光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 个答案:

答案 0 :(得分:6)

简短的回答是:

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

答案很长:请不要像这样混合常规的javascript和角度。重新编写代码,以便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
        });
}]);

答案 1 :(得分:4)

使用广播

//service 
var mydata = [];
this.update = function(){
  $http.get(url).success(function(data){
    mydata = data;
    broadcastMe();
  });
};
this.broadcastMe = function(){ 
  $rootScope.$broadcast('mybroadcast');
};

//controller
$scope.$on('mybroadcast', function(){
  $scope.mydata = service.mydata;
};

http://bresleveloper.blogspot.co.il/

编辑:几天前我学会了最佳实践 http://bresleveloper.blogspot.co.il/2013/08/breslevelopers-angularjs-tutorial.html

答案 2 :(得分:1)

我认为您最好使用高级角度服务进行数据传输,同时考虑承诺和服务:

http://docs.angularjs.org/api/ng.$q

答案 3 :(得分:0)

您需要将视图中的元素绑定到$scope对象的属性(简单或对象)。更新$ scope对象后,视图应自行更新。这就是AngularJS的美丽。

编辑: 请将您的控制器注册为

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

});

如果照片变量不可用,那么您可能必须使用变量创建服务并注入控制器。