簡體   English   中英

AngularJS指令轉換scope = false?

[英]AngularJS directive transclude scope=false?

如何通過transclude來防止指令創建新的范圍?

這個jsfiddle我不能綁定任何東西,因為新的范圍用紅色邊框說明。

HTML:

<div ng-app="components">
    <input ng-model="var">
    <block>
        123
        <input ng-model="var">
    </block>
</div>

JavaScript的:

angular.module('components', []).directive('block',function(){
    return{
        scope:false,
        replace:true,
        restrict:"E",
        transclude:true,
        template:'<div class="block" ng-transclude></div>',
        link:function(scope, el, attrs, ctrl){

        }
    }
});

CSS:

.ng-scope{
  border:1px solid red;
    margin:10px;
}

它實際上是預期的行為,如此處所述(ng-transclude創建子范圍): https//github.com/angular/angular.js/issues/1056並在此處討論: https//groups.google.com/forum /#!味精/角/ 45jNmQucSCE / hL8x48-JfZIJ

您可以通過在范圍(obj.var)中的對象上設置成員來解決此問題,就像在這個小提琴中一樣: http//jsfiddle.net/rdarder/pnSNj/10/

雖然Angular團隊不推薦這樣做,但另一種解決方法是在transcluded部分中顯式調用$ parent范圍:

<div ng-app="components">
    <input ng-model="var">
    <block>
        123
        <input ng-model="$parent.var">
    </block>
</div>

暫無
暫無

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

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