Rahul RD Rahul RD - 3 months ago 22
AngularJS Question

AngularJs get data from $http before controller init

I have a simple angularjs application, in which I want to run a slider and the slider elements come from $http request.

Here is the code for reference:

var mainApp = angular.module("myapp", []);

mainApp.run(['$rootScope', '$http',
function($rootScope, $http) {
$http.post('process.php?ajax_type=getChild').success(function(data) {
if (data.success) {
console.log(data.child); // data received...
$rootScope.categories = data.child;
}
});
}]);

mainApp.controller('gridChildController', function($scope, $http, $rootScope) {
console.log($rootScope.categories); // this is also null....
$scope.brands = $rootScope.categories;
$scope.finished = function(){
jQuery('.brand_slider').iosSlider({
desktopClickDrag: true,
snapToChildren: true,
infiniteSlider: false,
navNextSelector: '.brands-next',
navPrevSelector: '.brands-prev',
lastSlideOffset: 3,
onSlideChange: function (args) {

}
});
};
});


Here is code of the template file:

<div ng-app="myapp">
<div ng-controller="gridChildController" class="brand_slider" >
<div class='slider'>
<div class="slide col-md-5ths col-sm-4 col-xs-12 text-center" ng-repeat="x in brands" ng-init="$last && finished()">
<a href="{{x.link}}"><img class="img-responsive center-block" ng-src="{{x.image}}" title="{{x.title}}" alt="{{x.title}}"></a>
</div>
</div>
</div>
</div>


When I run this code, I get the data from the $http but ng-repeat doesn't work, and in the controller I get data null.

Answer

If you put something on $rootScope it will be also available on the child scopes. So you can bind straight to categories (no need to copy it to $scope.brands):

ng-repeat="x in categories"