Abhishek Abhishek - 9 months ago 41
AngularJS Question

AngularJS - Dynamic Checkboxes to hide/show Divs

I'm new to front-end web development. I am creating checkboxes dynamically using AngularJS.

<div ng-repeat="x in Brands" style="margin-left: 20px">
<input type="checkbox" ng-model="newObject[x.product_brand]">
<label> {{ x.product_brand }} </label>
</div>


Following the methods given on the links below, I want to hide/show divs using
using the dynamically created checkboxes.


  1. Dynamic ng-model

  2. ng-show



Here's the code-

<div class="item panel panel-default" ng-repeat="x in Brands" ng-show="newObject[x.product_brand]">
<div class="panel-heading">
{{x.product_brand}}
</div>
<div class="panel-body">
</div>
</div>


Controller-

app.controller('BrandController', function($scope, $http) {
getProductsInfo();

function getProductsInfo() {
$http.get("sql.php").success(function(data) {
$scope.Brands = data;
});
};
});


But it is not working. Checking/Unchecking the checkboxes does nothing.

lin lin
Answer Source

I think you need something like this runnable fiddle. This kind of handle is easy to manage with AngularJS. Welcome =) !!! Please note: The $timeout is to simulate your async $http request - its not a part of the solution.

View

<div ng-controller="MyCtrl">
  <div ng-repeat="x in Brands" style="margin-left: 20px">
     <input type="checkbox" ng-model="x.active">
     <label> {{ x.product_brand }} </label>
  </div>
  <div class="item panel panel-default" ng-repeat="x in Brands" ng-show="x.active">
    <div class="panel-heading">
        {{x.product_brand}}
    </div>
    <div class="panel-body">
    </div>
</div>
</div>

AngularJS demo application

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

myApp.controller('MyCtrl', function ($scope, $timeout) {

   $scope.Brands = [];

   init();

   function init () {
        $timeout(function () {
            $scope.Brands = [{
                product_brand: 'brand 1'
            },{
                product_brand: 'brand 2'
            },{
                product_brand: 'brand 3'
            },{
                product_brand: 'brand 4'
            }];
        });
   }
});