AngularJS update View after Model loaded from Ajax

前端 未结 4 662

I\'m newbie of angularjs developing and i wrote this simple app, but don\'t understand how i can update view, after the model il loaded from ajax request on startup!

相关标签:
4条回答
  • 2020-12-28 22:11

    I think you're better off using high level angular services for data transfer, also look into promises and services:

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

    0 讨论(0)
  • 2020-12-28 22:14

    You need to bind an element in your view to a property (simple or object) of your $scope object. Once the $scope object is updated the view should be updated on its own. That is the beauty of AngularJS.

    EDIT: Please register your controller as

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

    If photos variable is not available, then you might have to create a service with the variable and inject in the controller.

    0 讨论(0)
  • 2020-12-28 22:24

    use broadcast

    //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/

    EDIT:couple of days ago i've learned the best practice http://bresleveloper.blogspot.co.il/2013/08/breslevelopers-angularjs-tutorial.html

    0 讨论(0)
  • The short answer is this:

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

    The long answer is: Please don't mix regular javascript and angular like this. Re-write your code so that angular knows what's going on at all times.

    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
            });
    }]);
    
    0 讨论(0)
提交回复
热议问题