【问题标题】:AngularJS timing issues with controller, AJAX, ng-repeat, and directiveAngularJS 控制器、AJAX、ng-repeat 和指令的计时问题
【发布时间】:2014-07-25 17:57:33
【问题描述】:

几天前我刚开始使用 AngualrJS(喜欢它)使用 myApp 示例,但我还没有完全掌握一些事件时间安排。

我有一个启动 templateURL 和控制器的路由器。 templateURL 是一个部分,它使用 ng-repeat 循环我用控制器加载的 JSON。如果控制器包含静态 JSON,它似乎可以按我的意图工作,但是当我使用 $http 加载 JSON 时,我开始遇到时间问题:

  • 在 $http 返回之前的部分解释在图像路径之类的东西可以被替换之前抛出 404 -> "{{album.thumbnail}}.jpg"
  • 我还有一个指令,在控制器启动异步 $http 调用后触发一次,然后在控制器内实际完成 $http 调用后再次触发(理想情况下,我只希望它在 $http 完成后触发一次)

我的意图是使用通过 $http 检索专辑 JSON 数据,使用 ng-repeat 循环遍历模板以构建我的画廊。完成循环后,我想调用一个最终函数,为画廊提供类似 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>

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您似乎忘记在 http get 调用中将 $scope.last 设置为 true?您是否打算在 http 调用返回后将其设置为 true?如果是这样,您可以对将 ng-hide 设置为 $scope.last 的值的部分执行类似的操作。所以它会隐藏盒子的内容(以及在正确插值之前断开的链接),直到设置了正确的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多