Ionic:我如何只从我的json文件中加载1张图片?

时间:2015-08-09 21:15:47

标签: javascript html json angularjs ionic

我设法将我的json文件中的所有图像加载到应用程序中,但我只想加载1张图像。我使用ng-repeat这就是为什么它不断重复。我用什么替换ng-repeat所以它只显示第一张图像?

这是我的代码。

HTML:

<div ng-click="onClick()">
  <i class="ion-images"></i>
</div>
<a ng-controller="Ctrl">
  <ion-scroll direction="x">
    <img on-hold="onHold()" ng-repeat="image in data" ng-src="{{image.image}}" />
  </ion-scroll>
</a>

js:

.controller(&#34; Ctrl&#34;,function($ scope,$ http,$ ionicModal){

$scope.data = [];

$http.get('')
  .success(function(data) {
    $scope.data = data;
    window.localStorage.setItem("images", JSON.stringify(data));
  })
});

1 个答案:

答案 0 :(得分:1)

如果您只希望显示阵列中的第一个元素,则不能使用ng-repeater,您可以使用数组索引访问它,即:

ng-src="{{data.under9s[0].image}}

请参阅下面的工作演示:

&#13;
&#13;
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $http) {
  $scope.data = [];

  $http.get('https://api.myjson.com/bins/4tutm')
    .success(function(data) {
      $scope.data = data;
      window.localStorage.setItem("images", JSON.stringify(data));
    })
    .error(function(error) {
      if (window.localStorage.getItem("images") !== undefined) {
        $scope.data = JSON.parse(window.localStorage.getItem("images"));
      }
    });

});
&#13;
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>
  <ion-scroll direction="x">
    <img on-hold="onHold()" ng-src="{{data.under9s[0].image}}" ng-click="showImages($index)" class="image-list-thumb" />
  </ion-scroll>
</body>

</html>
&#13;
&#13;
&#13;