2

I am new to AngualrJS. And I am wondering, if ther is some way to toggle between different DIV's.

Let's say, in I have a menu, and by clicking on it, I would like to close current DIV, and open a new one.

A the moment if I one dive is opened and Im clicking at the another one it also appear.

Does any one have an idea, hot to handel this out?

HTML:

<div ng-app="app">
    <div ng-controller="MainController">
        <div>
            <ul>
                <li data-ng-repeat="Menu in Menus">
                    <a class="" href="#" ng-click="show=toggle(Menu)">
                        {{Menu.id}}
                    </a>

                </li>
            </ul>
        </div>
        <div data-ng-repeat="Menu in Menus" ng-show="Menu.show">
             <h2>
                     {{Menu.text}}
                </h2>

        </div>
    </div>
</div>

And JS:

angular.module('app', []).

controller('MainController', ['$scope', function ($scope) {
    $scope.Menus = [{
        id: 1,
        text: "This is first DIV!!!",
        show: true
    }, {
        id: 2,
        text: "This is second DIV!!!",
        show: false
    }, {
        id: 3,
        text: "This is third DIV!!!",
        show: false
    }];

    $scope.toggle = function (Menu) {
        Menu.show = !Menu.show;        
        return Menu.show;

    };


}]);

2 Answers 2

2

You can hide all menus and only show the selected one, change your toggle function like this :

$scope.toggle = function (Menu) {
    $scope.Menus.forEach(function(m) {
        m.show = (Menu==m);
    });
};

Update:

here's a better alternative, less and faster code :

you can get rid of the show property on your data and change the toggle function to

$scope.toggle = function (Menu) {
    $scope.activeMenu = Menu.id;
};

and change your ng-show to ng-show="Menu.id==(activeMenu || 1)"

here's a working example : https://refork.codicode.com/xc23

hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is what I was looking for. I was also keep trying, and came up, to some thing simular, can you comment please, what do yiu think about my solution? jsfiddle.net/djonkwt/x40ure3f/2 Thank you in advance.
-1

I would add a function that sets the current menu to hide. Then it would show the preferred menu.

$scope.toggle = function toggle(menu) {
  angular.forEach($scope.Menus, function(menuIndex) {
    menuIndex.show = false;
  })
  menu.show = true;
}

Did I understand your question correctly?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.