2

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.

Community
  • 1
  • 1
Abhishek
  • 95
  • 1
  • 1
  • 8

2 Answers2

2

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'
            }];
        });
   }
});
lin
  • 17,956
  • 4
  • 59
  • 83
1

Probably it is not working because you never defined newObject on the $scope. So actually you are trying to access undefined[x.product_brand].

Something like $scope.newObject = {}; in your Controller should do the trick.

user1660514
  • 267
  • 3
  • 7