2016-09-06 33 views
3

我正在使用ng-repat指令在我的HTML中放置自定義指令。使用ng-repeat在Angular 1.5.8中放置自定義指令不起作用

但是,自定義指令不被評估,如果直接在HTML上放置相同的指令,那麼它正在工作。

... 
    <body ng-app="docsSimpleDirective"> 
     <div ng-controller="Controller"> 
     <div>This is a Problem</div> 
    <!--Here in for loop i want to us the value to call a directive--> 

    <div ng-repeat="var in arr"> 

     <!--Here i am using directive with restrict: 'C' and this is not expending--> 
     <span class="{{var}}"></span> 
    </div> 


    <!-- here my directive named "direct" is working fine --> 
     <span class="direct"></span> 

    </div> 
    </body> 
... 

和我的JS代碼是

(function(angular) { 
    'use strict'; 
angular.module('docsSimpleDirective', []) 
    .controller('Controller', ['$scope', function($scope) { 
    $scope.arr = ['direct','indirect']; 
    }]).directive('direct', function() { 
    return { 
     template: 'direct', 
     restrict: 'C' 
    }; 
    }).directive('indirect', function() { 
    return { 
     template: 'indirect', 
     restrict: 'C' 
    }; 
    }); 
})(window.angular); 

我相信有一些編譯的問題,我搜索網頁,發現$編譯可以解決我的目的,但無法實施。

請幫我解決我的問題。

Plunker FPGA實現的相同:https://plnkr.co/edit/lYGg0UkQpNhN5NJx13Zj?p=preview

+1

它不工作,因爲當角解析器來'<跨度類= 「{{VAR}}」>'其編譯DOM&值評估'{{VAR}}'值,即意思是在DOM編譯之後'class'屬性值被填滿了,這就是爲什麼指令沒有被編譯。你可以通過使用'ng-switch' /'ng-if'指令來解決這個問題,在'ng-if' /'ng-switch'中把兩個指令'direct'&indendirect和一些'expression'放在一起。 –

回答

0

使用指令作爲一類是不好的做法,(因爲無法讀取) https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#restrict-to-elements-and-attributes

然後你傳遞一個指令爲一類,但動態插值這本身是壞的練習(https://docs.angularjs.org/guide/interpolation#known-issues)。插入類名稱並呈現該元素,但該指令在插值期間未編譯。

從您的指令定義的限制線,並把它們作爲屬性:

<span indirect></span> 

然後在NG-重複循環使用它們,你可以檢查,如果VAR =「直接」或「間接」

https://plnkr.co/edit/JUNFMCZASMntCnC6FsIO?p=preview

+0

ng -switch不會解決我的問題,因爲實際上我必須遍歷一個JSON並且有很大的no。的價值觀。我已經想到了擺脫ng-switch的指令,截至目前我已經實現了ng-swich和ng-include指令來解決我的目的。 –

+0

@ Shashank.gupta40與此相同http://stackoverflow.com/questions/38821980/how-to-write-directive-on-class-in-angular-js這是不可能的。看看$編譯的情況下,但你最好重新考慮你正在構建的東西。 – gyc

0

使用指令這樣

<div ng-repeat="var in arr"> <span direct ng-if="var == 'direct'"><span> <span indirect ng-if="var == 'indirect'"><span> <div>

並在控制器中將restrict定義爲屬性。

.directive('direct', function() { return { template: 'direct', restrict: 'A' };

相關問題