NG单击不加载图像AngularJS

时间:2018-09-21 02:00:02

标签: angularjs angularjs-ng-click

我有一个简单的模型,上面列出了名称和相应的图像。我正在尝试单击图像的名称并加载相应的图像。我无法加载图像。名称列表显示在页面上,但是当我单击它们时,什么也没有发生。请帮助代码。谢谢!

<!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">

  <div ng-repeat = "cat in options.catList">
    <h3 ng-click = "MainController.selectCat($index)">{{cat.name}}</h3>

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

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

  </div>

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

JS

(function() {

"use strict";


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

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

$scope.options = {

   catList:[

{
  name:  'Fluffy',
  images: 'images/Fluffy.jpeg'
},
{
  name: 'Tabby',
  images: 'images/tabby.jpeg'
 }
],
};

vm.selectCat=function(pos) {
vm.selectedCat = angular.copy(vm.catList[pos]);
vm.selectedCat.pos = pos;
};

activate();

function activate() {

}

})

})();

1 个答案:

答案 0 :(得分:1)

您正在混合$作用域和vm,采用一种方法。您需要在模板中使用controller作为语法,

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

演示

(function() {

"use strict";


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

angular.module('myApp').controller('MainController', function($scope) {
var vm = this;
 vm.selectCat = selectCat;
this.options = {
catList:[
{
  name:  'Fluffy',
  images: 'images/Fluffy.jpeg'
},
{
  name: 'Tabby',
  images: 'images/tabby.jpeg'
 }
],
};

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

})

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
    <meta charset="UTF-8">
    <title>Cat Clicker</title>
 
<body>

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

  <div ng-repeat = "cat in vm.options.catList">
    <h3 ng-click = "vm.selectCat(cat)">{{cat.name}}</h3>

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

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

  </div>

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