简体   繁体   中英

Show / Hide elements with AngularJs

I was trying to show and hide an element child, so when I hover over a <li> element, I set up a ng-show with value false for all the elements. If I try to make the value true to show, it shows me all the child elements. I just want to display for each element hovered its child:

HTML CODE:

<ul ng-init="show=false">
    <li>
        <a class="list-group-menu" href="#"><div class="icon-user"></div></a>
        <div ng-show="show"> Profile </div>
    </li>
    <li>
        <a class="list-group-menu" href="#"><div class="icon-scope"></div></a>
        <div ng-show="show"> Scope </div>
    </li>
    <li>
        <a class="list-group-menu" href="#"><div class="icon-job"></div></a>
        <div ng-show="show"> Job </div>
    </li>

    <li>
        <a class="list-group-menu" href="#"><div class="icon-login"></div>
            <div ng-show="show"> Login </div>
        </a>
    </li>
    <li>
    <a class="list-group-menu" href="#"><div class="icon-register"></div></a>
     <div ng-show="show"> Register </div>
    </li>
</ul>

JQUERY CODE:

$('ul li').mouseenter(function() {

   $(this).children('div').show();

});

$('ul li').mouseleave(function() {

   $(this).children('div').hide();

});

This is not an angular way. You should do like this.

JS

angular.module("firstApp").controller("myCtrl",function($scope) {
    $scope.allMenu = ["Profile","Scope","Job","Login","Register"];
});

HTML

<ul ng-controller="myCtrl">
    <li ng-repeat="menuName in allMenu" ng-mouseenter="show=true" ng-mouseleave="show=false">
        <a class="list-group-menu" href="#"><div class="icon-user"></div></a>
        <div ng-show="show"> {{menuName}} </div>
    </li>
</ul>

You don't need any javascript here at all. This is pure CSS task:

.menu .list-group-menu + div {
    display: none;
}
.menu .list-group-menu:hover + div {
    display: block;
}

for HTML:

<ul class="menu">
    <li>
        <a class="list-group-menu" href="#">
            <div class="icon icon-user">User</div>
        </a>
        <div>Profile</div>
    </li>
    <li>
        <a class="list-group-menu" href="#">
            <div class="icon icon-scope">Scope</div>
        </a>
        <div>Scope</div>
    </li>
    ...

You are binding all of the elements to the "show" variable, so when you flip it to true, all elements will show. If you want to use ng-show for that purpose, use an array of objects containing all of the data for the template and an ng-repeat. That will not only solve your problem but also DRY your template. I would slso suggest you look into $element so that you can stick to the angular environment and syntax instead of also having to use jquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM