Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS update View after Model loaded from Ajax

Tags:

ajax

angularjs

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!

This code don't work when I add delay into photos.php, using: sleep(3); for simulate remote server delay! instead if search.php is speedy it work!!

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

output of 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>

EDIT 1, Defer solution:

.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, Service solution:

... 
//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();
})
...
like image 489
stefcud Avatar asked May 05 '13 22:05

stefcud


2 Answers

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
        });
}]);
like image 95
Ben Cull Avatar answered Nov 15 '22 08:11

Ben Cull


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

like image 25
bresleveloper Avatar answered Nov 15 '22 08:11

bresleveloper