Dabbas Dabbas - 7 days ago 6
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
ngIf
but didn't work.

Is there a way to achieve this idea ?

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

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

Answer

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) {
              if(attrs.target){
                 $(element).after(attrs.target);
               }
            } else {
                var targetElement = $(element).next().clone();
                attrs.target = targetElement;
                $(element).next().remove();
            }
        }, 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 -->
  <div>Test</div>
</div>

Comments