AngularJs在控制器init之前从$ http获取数据

时间:2016-08-24 06:19:37

标签: javascript angularjs

我有一个简单的angularjs应用程序,我想运行一个滑块,滑块元素来自$ http请求。

以下是供参考的代码:

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) {

            } 
        });
    };
});

以下是模板文件的代码:

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

当我运行此代码时,我从$ http获取数据但ng-repeat不起作用,并且在控制器中我得到数据为空。

1 个答案:

答案 0 :(得分:0)

如果您在$rootScope上放置了某些内容,它也可用于子范围。因此,您可以直接绑定到categories(无需将其复制到$scope.brands):

ng-repeat="x in categories"