NewBoy NewBoy - 5 months ago 23
AngularJS Question

Angular Show and hide JSON objects individually

I am grabbing data from a JSON file, each object has it's on individual message. At the moment i am struggling to find a way show and hide messages separately. For example when i click on object i want to display credentials from that object only and not show credentials from the other objects.

var app = angular.module('app', []);

app.controller('mainCtrl', function($scope) {
$scope.colors = [
{
"color":"red",
"value":"#f00",
"message":"Simple message"
},
{
"color":"green",
"value":"#0f0",
"message":"Message with <strong>HTML</strong> tags"
},
{
"color":"blue",
"value":"#00f",
"message":"Am I going to work? I should not!"
}
]

$scope.popupBtn = function (message) {

$scope.currentMessage = message;

if (!($scope.popupBlock)) {
$scope.popupBlock = true;
}
}


});


HTML

<body ng-controller="mainCtrl">
<ul class="block-elements">
<li ng-repeat="details in colors">
<button ng-click="popupBtn(details.mesage)" ng-style="{ color: details.color }">Click Me</button>
</li>
</ul>

<div class="alert-block" ng-class="{'popup-container': popupBlock}">
<div ng-repeat="text in colors">
<a>{{text.message}}</a>
</div>
</div>

</body>

Answer

It's better if you treat the data inside your view separate from the controller.

var app = angular.module('app', []);

app.controller('mainCtrl', function($scope) {
 $scope.colors = [  
 {  
    "color":"red",
    "value":"#f00",
    "message":"Simple message"
 },
 {  
    "color":"green",
    "value":"#0f0",
    "message":"Message with <strong>HTML</strong> tags"
 },
 {  
    "color":"blue",
    "value":"#00f",
    "message":"Am I going to work? I should not!"
 }
 ]
 
   $scope.currentMessage = "";

   $scope.popupBtn = function (message) {

     // set current message
     $scope.currentMessage = message;

     // if popup is not open, open it
     if (!($scope.popupBlcok)){

       $scope.popupBlock = true;

     }
   }


 });
.alert-block {
  background-color: coral;
  color: white;
  display: none;
 }

.popup-container {
  display: block;
}
<body ng-app="app">
<div ng-controller="mainCtrl">
  <ul class="block-elements">
    <li ng-repeat="details in colors">
      <button ng-click="popupBtn(details.message)" ng-style="{ color: details.color }">Click Me</button>
    </li>
  </ul>

  <div class="alert-block" ng-class="{'popup-container': popupBlock}">
    <div>
      <a>{{currentMessage}}</a>
    </div>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
 </div>
</body>

Comments