2016-03-03 78 views
1

这是JS文件插入图片只有一次

(function(){ 
    var app = angular.module('myApp', []); 

    app.controller('appController',[ '$scope', '$http', function($scope, $http){ 
     $http.get('auto_data.json').then(function(quizData){ 
      $scope.myQuestions = quizData.data;   
     }); 
    }]); 

})(); 

这是JSON

{ 
    "question" : "Saturn is the ______ planet from the Sun.", 
    "image" : "images/category/1.jpg", 
    "answers" : [ 
     {"id" : 0, "text" : "Fourth" }, 
     {"id" : 1, "text" : "Sixth" }, 
     {"id" : 2, "text" : "Second" }, 
     {"id" : 3, "text" : "Eight" }   
    ], 
    "correct" : 1 
} 

这是我的HTML

<!DOCTYPE HTML> 
<html ng-app="myApp"> 

<div id="myQuiz" ng-controller="appController"> 
    <div ng-repeat="myQuestion in myQuestions " > 
     <h2 class="txt" >{{myQuestion.question}}</h2> 
     <div ng-repeat="answer in myQuestions[$index].answers"> 
      <p>{{answer.text}}</p> 
      <img ng-src="{{myQuestion.image}}" > 
     </div> 
    </div> 
</div> 

<script src="js/angular.min.js"></script> 
<script src="js/quiz_test.js"></script> 
</html> 

在这种情况下,图像在页面上显示3次。如何让图像只显示一次?

+3

您应该将带有{{myQuestion.image}}的'img'标记移出内部'ng-repeat'。 –

+0

谢谢你的回答。 – dragon

+0

我还会注意到的一件事是在你的内部ng-repeat中,你正在使用myQuestions [$ index],它与循环中的当前myQuestion对象完全相同。 – mhodges

回答

0

<img ng-src="{{myQuestion.image}}" >移到低于</div>的当前位置。它多次显示,因为它在ng-repeat中被捕获。

0

您可以将图像置于内部ng-repeat之外,也可以通过$ index有条件地显示图像。

<div ng-repeat="myQuestion in myQuestions"> 
... 
    <div ng-repeat="answer in myQuestion.answers"> 
     <p>{{answer.text}}</p> 
     <img ng-src="{{myQuestion.image}}" ng-if="$index == 0"/> 
    </div> 
</div>