2016-11-26 123 views
0

我想要做的是以下幾點:如何在html註釋中使用ngIf?

<!-- 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 --> 

我試圖建立自己的ngIf,但沒有奏效。
有沒有辦法實現這個想法?
爲什麼要使用html註釋?因爲樣式將在<head>標籤不允許<div>或其他標記被用來在其添加ngIf,而且還因爲這些myStyle1.css, myStyle2.css, myStyle3.css將使用gulp任務與useref插件被壓縮成一個文件.css,所以我不能爲每個樣式標籤添加ng-if
也不能把link標籤內body和包裝它們div因爲有link標籤在<head>標籤和我需要尊重他們的順序。

回答

1

AngularJS有限制使用ng-if僅限於attributeA如下所示。所以,你不能在comment

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

使用此相反,你可以創建的是定製指令與如下限制M。我在下面寫的當前指令可用於每個元素的一條評論。如果您需要處理多個元素,則應該擴展指令。

注意:我用下面只有div顯示/隱藏價值link沒有任何顯示

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>

+0

正如我所說,我不能用' ng-if'在'link'上自動調用那些'.css'會被壓縮並轉換成一個'link'標籤,所以所有的屬性都會被刪除。 – Dabbas

+1

我會更新這個代碼 – Aruna

+0

我已經更新了代碼,請看看。 – Aruna