2014-04-16 58 views
0

我剛剛在幾天前開始使用myApp示例與AngualrJS(愛好它),但我還沒有完全掌握一些事件時序。AngularJS與控制器,AJAX,ng-repeat和指令的時序問題

我有一個路由器啓動一個templateURL和一個控制器。 templateURL是一個使用ng-repeat來循環使用控制器加載的JSON的部分。如果控制器包含靜態JSON似乎工作,我打算,但是當我加載使用$ JSON的HTTP我開始跑步進入時機的問題:

  • 的$ HTTP回報的事情像扔一個404之前的部分解釋圖像路徑,然後才能被替換 - >「{{album.thumbnail}} jpg」
  • 我也有一個指令,在控制器啓動異步$ http調用後觸發一次,並在$ http調用實際完成後再次觸發控制器(理想情況下,我只希望它在$ http完成後觸發一次)

我的意圖是使用檢索使用ng-repeat通過$ http專輯JSON數據循環播放模板以構建我的圖庫。一旦完成循環,我想調用一個最終的功能,讓畫廊有一個類似Pinterest的砌體佈局。這看起來像是一個非常典型的流程($ http - > ng-repeat - > final函數),所以在這一點上我必須缺少一些小東西。

期待更多地瞭解AngularJS ...

HTML

<!doctype html> 
<html lang="en" ng-app="myApp"> 
    <head> 
    <title>myApp</title> 
    </head> 
    <body> 

    <div ng-view></div> 

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js"></script> 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular-route.min.js"></script> 
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> 
    <script src="js/modernizr-transitions.js"></script> 
    <script src="js/jquery.masonry.min.js"></script> 
    </body> 
</html> 

模塊

angular.module('myApp', [ 
    'ngRoute', 
    'myApp.filters', 
    'myApp.services', 
    'myApp.directives', 
    'myApp.controllers' 
]) 
.config(['$routeProvider', function ($routeProvider) { 

    $routeProvider.when('/gallery', {templateUrl: 'gallery.html', controller: 'ctrlGallery'}); 
    $routeProvider.otherwise({redirectTo: '/gallery'}); 

}]); 

控制器

angular.module('myApp.controllers', []) 
.controller('ctrlGallery', ['$scope', '$http', function (lcScope, lcHttp) { 

    lcHttp.get("/services/gallery.php?start=1&count=12") 
    .success(function(data, status, headers, config) { 
    lcScope.albums = data.DATA; 
    }) 

}]); 

指令

angular.module('myApp.directives', []) 
.directive('postGalleryRepeatDirective', function() { 

    return function (scope, element, attrs) { 

    if (scope.$last) { 
     $('#container').masonry({ 
     itemSelector: '.box', 
     columnWidth: 250, 
     isAnimated: !Modernizr.csstransitions, 
     isFitWidth: true 
     }); 
    } 

    }; 

}); 

gallery.html部分

<div class="masonry" ng-controller="ctrlGallery"> 
    <div class="box masonry-brick" ng-repeat="album in albums" post-gallery-repeat-directive> 
    <a href="{{ album.link }}"> 
     <img src="/img/{{ album.thumbnail }}.jpg"> 
    </a> 
    <p>{{ album.name }}</p> 
    </div> 
</div> 

回答

0

好像你忘了設置$ scope.last到真正在你的HTTP GET打電話?您打算在http調用返回後將其設置爲true嗎?如果是這樣,你可以爲你設置隱藏到$ scope.last的值的部分做一些類似的事情。所以它會隱藏框的內容(並且斷開的鏈接預先進行正確的插值),直到設置了適當的值。