簡體   English   中英

AngularJS指令模板包含

[英]Angularjs directive template transclusion

我有一個像這樣的元素:

<input test class="foo bar" ng-model="foo" name="foo"/>

當它具有“ test”屬性時,我正嘗試將其轉換為以下示例:

<div class="something">
    <input type="text" class="foo bar" ng-model="foo" name="foo"/>
    <span>test</span>
</div>

但是我在包含問題上遇到了問題,而不是將屬性轉移到輸入中,而是將它們轉移到div中,所以最終得到類似以下內容:

<div class="something foo bar" type="text" ng-model="foo" name="foo">
    <input/>
    <span>test</span>
</div>

這是指令:

.directive('test', [function () {
     return {
        transclude:true,
        replace:true,
        template:'<div class="something">\
            <input ng-transclude>\
            <span>hi</span>\
        </div>',
        link: function (scope, element, attrs, ngModel) {
            // do stuff
        }
    }
}])

您將無法通過這種方式進行超越:

<input test class="foo bar" ng-model="foo" name="foo"/><!-- NO -->

我相信您最好的機會(使用元素級指令)是:

<test>
    <input class="foo bar" ng-model="foo" name="foo"/>
</test>

在這種情況下,指令的template為:

template:
    '<div class="something">\
        <ng-transclude />\
        <span>hi</span>\
    </div>',

我認為您可以嘗試以下指令:

JS

var app = angular.module('app',[]);
function myCtrl($scope){

}
app.directive("test",function(){
  return {
    template: '<div class="something"><input type="text" class="foo bar" ng-model="foo" name="foo"/><div ng-transclude></div></div>',
    transclude: true,
    replace: true
  };
});

的HTML

<div test ng-controller="myCtrl">
  <span>333</span>
</div>

輸出將鏈接此:

<div class="something ng-scope" test="" ng-controller="myCtrl">
  <input type="text" class="foo bar ng-pristine ng-valid" ng-model="foo" name="foo">
  <div ng-transclude="">
    <span class="ng-scope">333</span>
  </div>
</div>

jsfiddle演示

希望這對您有幫助

顯然,可以從AngularJS irc頻道中獲得Foxandxss的鏈接。

http://plnkr.co/edit/7gOQEODWlJMV9Fe9a9YV?p=preview

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM