【问题标题】:Angularjs – Initializing script after ng-repeat does not work with http getAngularjs – ng-repeat 后初始化脚本不适用于 http get
【发布时间】:2015-04-27 19:26:59
【问题描述】:

我正在尝试在我的指令创建的渲染元素上启动轮播脚本。如果我用静态 json 提供指令,它会起作用,但如果我使用 http get 从 api 获取数据,它将无法正确初始化。虽然脚本确实初始化并创建了一组用于轮播导航的元素,但似乎渲染的元素在发生这种情况后被注入。

如果我将初始化延迟 100 毫秒,它将正确初始化,但感觉就像一个 hacky 解决方案。在这种情况下,最佳做法是什么?

静态数据 - 有效

angular.module('exhibitions', [])
  .directive('exhibitionsCarousel', ['$timeout', function(timer) {
    return {
      scope: {},
      link: function(scope, element, attrs) { 

        var initFlickity = function () {
          var flkty = new Flickity( '.main-gallery', {
            cellAlign: 'left',
            contain: true
          });
        };

        timer(initFlickity, 0);

      },
      templateUrl: '/app/themes/pomgallery/exhibitions_carousel.html',
      replace: true,
      controller: 'exhibitionsCarouselCtrl',
      controllerAs: 'ctrl'
    };
  }])
  .controller('exhibitionsCarouselCtrl', function($scope, $http) {
    this.exhibitions = [
      {title: 'Rachel', date: 'Washington', place: 'One'},
      {title: 'Joshua', date: 'Foster', place: 'Two'},
      {title: 'Samuel', date: 'Walker', place: 'Three'}
    ]; 
  });

angular.module('PomGallery', ['exhibitions']);

获取的数据 - 无法立即工作

angular.module('exhibitions', [])
  .directive('exhibitionsCarousel', ['$timeout', function(timer) {
    return {
      scope: {},
      link: function(scope, element, attrs) { 

        var initFlickity = function () {
          var flkty = new Flickity( '.main-gallery', {
            cellAlign: 'left',
            contain: true
          });
        };

        timer(initFlickity, 0); // If I set it to 100 rather than 0 it'll work.

      },
      templateUrl: '/app/themes/pomgallery/exhibitions_carousel.html',
      replace: true,
      controller: 'exhibitionsCarouselCtrl',
      controllerAs: 'ctrl'
    };
  }])
  .controller('exhibitionsCarouselCtrl', function($scope, $http) {

    var vm = this;
    $http({
      method: 'GET',
      url: '/wp-json/posts',
      params: {
        'filter[posts_per_page]': 3
      },
    }).
    success( function( data, status, headers, config ) {
      vm.exhibitions = data;
    }).
    error(function(data, status, headers, config) {});
  });

angular.module('PomGallery', ['exhibitions']);

【问题讨论】:

    标签: javascript angularjs timer get


    【解决方案1】:

    你应该使用一个承诺。 Promise 会在显示数据之前等待数据,但它仍会在控制器中运行其他函数,类似于 c# 中的异步函数。这是教程的链接 https://docs.angularjs.org/api/ng/service/$q

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多