Issue
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;
};
}]);
Solution
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.
Answered By - Chtioui Malek
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.