2017-02-22 10 views
0

を引き起こす:AngularJS問題、私は次のコードを持っている

app.controller('carouselCtrl', ['$scope', '$http', function($scope, $http){ 
    $http.get('/app/ajax/get-favs.php').then(function(response){ 
     $scope.slides = response.data; 
    }); 
}]); 

app.directive('slider', function($timeout) { 
    return { 
     restrict: 'AE', 
     replace: true, 
     scope: { 
      slides: '=' 
     }, 
     link: function(scope, elem, attrs) { 
      scope.currentIndex=0; 

      [...] 

      scope.$watch('currentIndex', function(){ 
       scope.slides.forEach(function(slide){ 
        slide.visible=false; 
       }); 
       scope.slides[scope.currentIndex].visible=true; 
      }); 
     }, 
     templateUrl: '/app/includes/slider.html' 
    }; 
}); 

マイブラウザのコンソールに戻ります:

Error: scope.slides is undefined .link/ [...] in line 55 (scope.slides.forEach....)

をしかし、私は$ scope.slidesを書く場合は$ httpで取得代わりに、手動でオブジェクト。アプリケーションが正しく動作するようにしてください。つまり、scope.slidesオブジェクトをスコープ内のディレクティブから呼び出すことはできません。$ watch。

どういうところが間違っていますか?

+1

あなたは 'slider'と' carouselCtrl'を囲むHTMLを投稿することができますか? –

+0

私はディレクティブでスライドを定義する理由はよく分かりません。あなたのスライドをディレクティブに渡すのではなく、取り出すことができるからです。 httpコールが解決される前に、Angularがすでにディレクティブをダイジェストしています。 – Rob

答えて

1

ページを初期化するとき、scope.slidesはまだ存在しません(=それはundefinedです)。 api呼び出しが完了した時点でのみ値を取得します。あなたのディレクティブでscope.slidesの有無のチェックを追加します。

scope.$watch('currentIndex', function(){ 
    if (!scope.slides) return; // Added row 
    scope.slides.forEach(function(slide){ 
    slide.visible=false; 
    }); 
    scope.slides[scope.currentIndex].visible=true; 
}); 
関連する問題