Search code examples
angularjsangularjs-ng-click

NG-Click not Loading Image AngularJS


I have a simple model with a list of names and corresponding images. I'm trying to click on the name of the image and load the corresponding image. I can't get the image to load. The list of names appears on the page, but when I click them nothing happens. Please help with code. Thx!

<!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() {

}

})

})();

Solution

  • You are mixing up $ scope and vm, go with one approach. You need to use controller as syntax in the template,

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

    DEMO

    (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>