Jack The Baker
Jack The Baker

Reputation: 1903

Angular toggle show/hide based on attribute

Here is my Angular code:

<div ng-repeat="messages" ng-hide="isAdmin" data-type="{{msg.typetext}}">
</div>

The html output is:

<div ng-repeat="messages" ng-hide="isAdmin" data-type="1">Some Text</div>
<div ng-repeat="messages" ng-hide="isAdmin" data-type="0">Some Text</div>
<div ng-repeat="messages" ng-hide="isAdmin" data-type="1">Some Text</div>

These div s has an attribute called data-type and I am trying to filter these items based on this attribute with two buttons, 1 mean admin and 0 mean others.

Buttons:

<button type="button" ng-click="isAdmin=true">
Admin
</button>
<button type="button" ng-click="isAdmin=false">
Other
</button>
<button type="button" ng-click="isAdmin=false">
All
</button>

What I got so far is, show/hide div. How can I toggle show/hide div based on this attribute?

What I want to achieve is, If click Admin Button, should just show div that has data-type="1" and if click on Other Button, should just show div that hasdata-type="0" and if click on All Button, should show all div.

Upvotes: 0

Views: 450

Answers (2)

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38693

@Rahul did it while am typing my answer. Here is my code:

angular.module("test",[]).controller("testc",function($scope) {   
      $scope.data=[{"typetext": "0","role": "User"},{"typetext": "1","role": "Admin"}]; });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="testc">
   <div ng-repeat="value in data" ng-show="value.typetext==IsAdmin || IsAdmin==undefined">
   {{value.typetext}}
</div>
<input type="button" ng-click="IsAdmin=1"  value="Admin"/>
<input type="button" ng-click="IsAdmin=0"  value="User"/>
<input type="button" ng-click="IsAdmin=undefined" value="All"/>
</div>

Upvotes: 1

Rahul Sharma
Rahul Sharma

Reputation: 10111

try this

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">


<div ng-repeat="msg in message" ng-show="select == msg.typetext || select == '2'">{{msg.msg}}
</div>  


<button type="button" ng-click="select=1">
  Admin
</button>
<button type="button" ng-click="select=0">
  Other
</button>
<button type="button" ng-click="select=2">
  All
</button>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
	$scope.select = 2;
  $scope.message = [
   {typetext:1,msg:'admin'},
   {typetext:0,msg:'other'}
  ]
});
</script>

</body>
</html>

Upvotes: 1

Related Questions