Pawan
Pawan

Reputation: 32321

Angular JS On Check / Uncheck Of Checkbox Add And Remove Corresponding HTML

On Check/Uncheck of the CheckBox , I am trying to add Or Remove the Corresponding HTML dynamically

On Click of the One Checkbox i want to add

var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.prepend('One'<br/>'); 

and on Click of the Two Checkbox i want to add along with One

 var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.prepend('Two<br/>'); 

I have tried as shown in below HTML ,On Uncheck but i am unable to Remove HTML

http://jsfiddle.net/9fR23/464/

Upvotes: 0

Views: 1004

Answers (1)

couzzi
couzzi

Reputation: 6366

Why not just use ng-repeat again to print out the values pushed in your $scope.selectedNames array?

By nature of having your repeated element be a <div> you get the line break for free. But, you could also do just as easily do <span ng-repeat="n in selectedNames">{{n}}<br /></span>

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

app.controller('myCtrl', function($scope) {
  $scope.names = ["One", "Two", "Three"];
  $scope.selectedNames = [];

  $scope.select = function(name) {
    var index = $scope.selectedNames.indexOf(name);
    if (index < 0) {
      $scope.selectedNames.push(name);

      var myEl = angular.element(document.querySelector('#divID'));
      myEl.prepend('' + name + '<br/>');
    } else
      $scope.selectedNames.splice(index, 1);
  }
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="myCtrl">
  <div ng-repeat="n in names">
    <input type="checkbox" ng-click="select(n)" />{{n}}
  </div>

  <div ng-repeat="n in selectedNames">{{n}}</div>
</body>

</html>

Mirror on Plunker: http://plnkr.co/edit/pAIpY4qZpT4SvLgCaYIy?p=preview

Upvotes: 1

Related Questions