Skip to content

Instantly share code, notes, and snippets.

@mcamiano
Last active December 20, 2015 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcamiano/6148519 to your computer and use it in GitHub Desktop.
Save mcamiano/6148519 to your computer and use it in GitHub Desktop.
ng-hide and ng-show do not modify the DOM so much as change a class. This attribute directive removes the contained content if the expression evaluates to true.

This is an improved alternative to the occlude directive. Suppose we want the occlude to happen dynamically, when a model changed. The other version of the occlude directive defined here would just be invoked once, at the time the link function is called on an instantiated template. Ideally, model changes should drive such DOM manipulations through watchers.

So let's set up a boolean select box. First some model driving the options in the controller:

  $scope.cfg={};
  $scope.cfg.boolean_options = [ {label: 'True', value:true}, {label: 'False', value:false} ];

  $scope.cfg.include_exclude = true;

then some HTML and angular directives to render the select box

<label>Hide stuff? <select ng-model="cfg.include_exclude" ng-options="b.value as b.label for b in cfg.boolean_options"></select></label>

<div class="hidden" amc-occlude="cfg.include_exclude">stuff we should not see</div>

and finally the new directive:

  mymodule.directive('amcOcclude', function() {
    return {
      link: function( scope, element, attributes ) {
        var content = element.html();
        scope.$watch('cfg.include_exclude', function() {
          if (!scope.$eval(attributes.occlude)) {
            element.html(content).removeClass('hidden');
          } else {
            element.html('');
          }
        });
      },
      priority: 1003,
      restrict: 'A'
    };
  })
mymodule.directive('amc-occlude', function() {
return {
link: function( scope, element, attributes ) {
var content = element.html();
if (!scope.$eval(attributes.occlude)) {
element.html(content);
} else {
element.html('');
}
},
priority: 1003,
restrict: 'A'
};
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment