How do I get ng-show to work in AngularJS?

47 Views Asked by At

I want an image to be displayed (over the top of another image) upon hovering over it's container. I am trying to get this to work with angular and ng-show however I cannot figure out where I am going wrong. The image with the ng-show attribute is never displayed.

<header class="header">
    <a routerLink="/">
        <div class="header__link" ng-controller="testCtrl"
             ng-init="show = false"
             ng-mouseenter="show = true"
             ng-mouseleave="show = false">
            <img class="header__link--logo" src="assets/img/logo2.jpeg">
            <img class="header__link--logo--hover" src="assets/img/logo2hover.jpeg"
                 ng-show="show">
            <h1 class="header__link--title">
                INMOCO
            </h1>
        </div>
    </a>
    <nav>

    </nav>
</header>
var app = angular.module("testApp", []);

console.log("app");

app.controller('testCtrl', function($scope){
    $scope.show = false;
});

Please help me understand why the angular specific code is not working or an easier way to do this. Thank you!

2

There are 2 best solutions below

0
georgeawg On

Be sure to include the ng-app directive:

<body ng-app="testApp">
    <!-- ... -->
</body>

The DEMO

var app = angular.module("testApp", []);

app.controller('testCtrl', function($scope){
    $scope.show = false;
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="testApp">
  <header class="header">
  <a routerLink="/">
     <div class="header__link" ng-controller="testCtrl"
             ng-init="show = false"
             ng-mouseenter="show = true"
             ng-mouseleave="show = false">
            <img class="header__link--logo" src="assets/img/logo2.jpeg">
            <img class="header__link--logo--hover" src="assets/img/logo2hover.jpeg"
                 ng-show="show">
            <h1 class="header__link--title">
                INMOCO
            </h1>
      </div>
    <nav>

    </nav>
  </header>
</body>

0
Jake Holzinger On

The images need to be styled with position: absolute or the "hover" image will not render on top of the "base" image. You can also control showing and hiding of the image entirely in CSS, using angular to do this is a bit overkill.

.image {
    height: 150px;
    position: absolute;
}

.hover-image {
    display: none;
}

.image-container:hover .hover-image {
    display: initial;
}
<div class="image-container">
    <img class="image base-image" src="https://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-12/256/slightly-frowning-face.png">
    <img class="image hover-image" src="https://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-12/256/slightly-smiling-face.png">
</div>