Dabbas Dabbas - 1 year ago 78
AngularJS Question

How to use ngIf in html comments?

What I'm trying to do is the following:

<!-- directive: ng-my-if condition -->
<link rel="stylesheet" ng-href="myStyle1.css">
<link rel="stylesheet" ng-href="myStyle2.css">
<link rel="stylesheet" ng-href="myStyle3.css">
<!-- end ng-my-if -->

I tried to build my own
but didn't work.

Is there a way to achieve this idea ?

Why to use html comments? because the styles will be in
tag which doesn't allow
or other tags to be used to add
in it, and also because those
myStyle1.css, myStyle2.css, myStyle3.css
will be compressed into one
file using
task with
plugin, so I can't add
for each style tag.

Also can't put
tags inside
and wrap them with
coz there's
tags up in the
tags and I need to respect the order of them.

Answer Source

AngularJS has a restriction to use ng-if only with attribute by A as something like below. so, you can't use this in comment

var ngIfDirective = ['$animate', function($animate) {
  return {
    transclude: 'element',
    priority: 600,
    terminal: true,
    restrict: 'A', 

Instead you can create a custome directive with restrict M as below. The current directive I have written below will work for one comment per one element. If you need to handle multiple element, the directive should be extended.

Note: I have used the div below only to show/hide the value as link don't have any display

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

app.controller('TestController', function($scope){
  $scope.checked = true;

app.directive('ngIfExt', function() {
    return {
      restrict: 'M',
      link: function(scope, element, attrs) {
        scope.$watch(attrs.ngIfExt, function(value, oldValue) {
            if(value) {
            } else {
                var targetElement = $(element).next().clone();
                attrs.target = targetElement;
        }, true);

angular.bootstrap(document, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="TestController">
  <input type="checkbox" ng-model="checked"/> Show/hide
  <!-- directive: ng-if-ext checked -->
  <link rel="stylesheet" ng-href="myStyle1.css">
  <!-- directive: ng-if-ext checked -->
  <link rel="stylesheet" ng-href="myStyle2.css">
  <!-- directive: ng-if-ext checked -->
  <link rel="stylesheet" ng-href="myStyle3.css">
  <!-- directive: ng-if-ext checked -->

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download