AngularJS Example

by Mahmoud bayyari

HTML

<div ng-controller="myCtrl">
  Click me:
  <input type="checkbox" ng-model="checked" />
  <br/>Red when not checked:
  <div id="div1" ng-batch-if check={{checked}}>
    <div class="x">ABC
      <p style="color:blue">abc</p>
    </div>
    <div>KLM</div>
    <div>PQR</div>
  </div>
  </div>

CSS

div#div1 {
  border: 1px solid red;
}

div#div2 {
  border: 1px solid blue;
}

JavaScript

angular.module('App', [])
  .controller('myCtrl', function($scope) {
    $scope.checked = true;
  })
  .directive('ngBatchIf', function($compile) {
    return {
      restrict: 'A',
      scope: {
        check: '@'
      },
      controller: function($scope) {},
      link: {
        pre: function(scope, elm, attrs) {
            attrs.$observe('check', function() {
              // After flattening, Angular will still have the first element
              // bound to the old scope, so we create a temporary marker 
              // to store it
              var contents = elm.contents();
              if (scope.check === "true") {
              console.log(scope.check);
              //  elm.prepend('<div  id="div2" check={{checked}}></div>');
              } else {
								console.log(scope.check);
                elm.replaceWith(contents);
                
               // elm.prepend('<div  id="div1" check={{checked}}></div>');
              }
            })
          }
          //elm.prepend('<div style="display: none"></div>');

        // Flatten (unwrap) the parent
        //var children = elm.children();
        //elm.replaceWith(children);

        // Add the ng-if to the children
        //if(attrs.ngBatchIf=="checked"){
      }
    }
  });