将初始图像加载到页面AngularJS

时间:2018-09-21 21:01:12

标签: angularjs image angularjs-ng-click

我有一个页面加载时来自模型的名称列表。当我单击名称时,来自模型的相应图像将出现在页面上。有没有办法在其中加载初始 图片[0]何时加载页面?这可以是随机图像,也可以是模型数据集中的第一个图像。

<!DOCTYPE html>
<html ng-app = "myApp"><head>
    <meta charset="UTF-8">
    <title>Cat Clicker</title>
    <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
    <link rel ="stylesheet" type "text/css" href ="clicker.css">

    <script type = "text/javascript" src="Libs/angular.js"></script>
    <script type = "text/javascript" src="js/CatClickerMe.js"></script>
<body>

<div ng-controller = "MainController as vm">

  <div ng-repeat = "cat in vm.options.catList">


    <h3 ng-click = "vm.selectCat(cat)">{{cat.name}}</h3>

    </div>
    <hr>


  <h3>{{vm.selectedCat.name}}</h3>



  <img ng-src ="{{vm.selectedCat.images}}">
  </div>

  </div>

</div>
</body>
</html>

JS

"use strict";


angular.module('myApp',[]);

angular.module('myApp').controller('MainController', function($scope) {
  var vm = this;

   vm.selectCat=selectCat;

vm.options = {

   catList:[

   {
    name:  'Fluffy',
    images: 'images/Fluffy.jpeg'
  },

  {
    name:  'Blacky',
    images: 'images/blacky.jpeg'
  },
  {
    name: 'Tabby',
    images: 'images/tabby.jpeg'
  },

  {
    name:  'Cleo',
    images: 'images/Cleo.jpeg'
  }
],
};

function selectCat(pos) {
  vm.selectedCat = pos;
};


});

2 个答案:

答案 0 :(得分:1)

可以尝试一下吗:-

"use strict";
angular.module('myApp',[]);

angular.module('myApp').controller('MainController', function($scope) {
  var vm = this;

   vm.selectCat=selectCat;

vm.options = {

   catList:[

   {
    name:  'Fluffy',
    images: 'images/Fluffy.jpeg'
  },

  {
    name:  'Blacky',
    images: 'images/blacky.jpeg'
  },
  {
    name: 'Tabby',
    images: 'images/tabby.jpeg'
  },

  {
    name:  'Cleo',
    images: 'images/Cleo.jpeg'
  }
],
};

function selectCat(pos) {
  vm.selectedCat = pos;
};
function Init(){
   vm.selectedCat = vm.options.catList[0];
}

Init();

});

答案 1 :(得分:1)

通过在vm.options下方设置vm.selectedCat加载第一张图像

vm.selectedCat = vm.options.catList[0];

下面是jsfiddle链接供您参考

jsfiddle:https://jsfiddle.net/Lpaudwf8/21/