简体   繁体   中英

Hide and show div in angularJS on click

I am creating 3 popups using ng-repeat for developing one filter. I want to do everything in Angular only, with every popup having same class name and a different id. On each button click I want to show one popup and I want to hide rest of them.

I got one code by using one scope variable and it is working fine. I want to know if there is any other better way to do this.

In jQuery we can do this with 2 line of code, but I don't know how to do this efficiently in Angular.

app.controller('MainCtrl', function($scope) {

    $scope.IsVisible = [false];

    $scope.mainList = [];
    var obj = {};
    obj.name = "swimlanes";
    obj.list = [];
    $scope.mainList.push(obj);
    obj = {};
    obj.name = "programs";
    obj.list = [];
    $scope.mainList.push(obj);
    obj = {};
    obj.name = "programs";
    obj.list = [];
    $scope.mainList.push(obj);


    //click event of rect trangle
    $scope.click = function(key, index) {
        var flag = $scope.IsVisible[index];
        $scope.IsVisible = [false];
        $scope.IsVisible[index] = !flag;
        $scope.myObj = {
            "top": key.currentTarget.offsetTop + "px",
            "left": key.currentTarget.clientWidth + 10 + "px"
        }
    }
});




   <div  ng-repeat="val in mainList" id={{val.name}} class="mainPopup" ng-    show="IsVisible[$index]" ng-style="myObj">

This will work fine but I want to know if there is any better way.

working code

The controller can be improved by replacing the $scope.IsVisible with a variable that simply points to the selected item in mainList. You then don't need to maintain an array of booleans.

$scope.selected = null;

$scope.click can then be changed to:

$scope.click = function(key, index) {
    $scope.selected = $scope.mainList[index];
    $scope.myObj = {
        "top": key.currentTarget.offsetTop + "px",
        "left": key.currentTarget.clientWidth + 10 + "px"
    }
};

In addition you will need to update your HTML to use the $scope.selected to control the visibility of the details:

<div  ng-repeat="val in mainList" id={{val.name}} class="mainPopup" ng-show="val == selected" ng-style="myObj"></div>

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