簡體   English   中英

AngularJS:指令轉換范圍丟失

[英]AngularJS : Directive transcluded scope lost

我正在構建一個指令,我正在調用'requires-authorization'來包裝ng-if指令。 我想用它如下:

<requires-authorization role='SuperUser'>
<!— super secret user stuff goes here, within
   the scope of this view's controller —>
</requires-authorization>

我已經達到了:

angular.module('myApp').directive('requiresAuthorization', function() {
   return {
    template: '<div ng-if=\'iAmInRole\' ng-transclude></div>',
    restrict: 'E',
    transclude: true,
    scope: {
        role: '@'
    },
    controller: function($scope, UserService) {
       $scope.iAmInRole = (UsersService.myRoles.indexOf($scope.role) !== -1);
    }
  };
});

這是有效的,但指令中包含的內容會失去其范圍,特別是它在其中找到的視圖的控制器的范圍。 我在俯瞰什么?

jsfiddle供參考: http//jsfiddle.net/HbAmG/8/注意如何在指令中顯示auth值,但在指令外可用。

ng-ifng-transclude指令都在您的指令中執行轉義。 在這種情況下,內置轉換機制不能正常工作,您應該實現自己的ngIf以使其按預期工作:

JavaScript的

app.directive('requiresAuthorization', function () {
    return {
        template: '<div ng-transclude></div>',
        restrict: 'E',
        transclude: true,
        scope: {
            role: '@'
        },
        controller: function ($scope) {
            $scope.iAmInRole = true;
        },
        link: function(scope, element, attr, ctrl, transcludeFn) {
            transcludeFn(function(clone) { // <= override default transclude
                element.empty();
                if(scope.iAmInRole) { // <= implement ngIf by yourself
                  element.append(clone);
                }
            });
        }
    };
});

Plunker: http ://plnkr.co/edit/lNIPoJg786O0gVOoro4z?p=preview

如果ng-show是您使用的選項而不是ng-if它也可能是一個非常簡單的解決方法。 唯一的副作用是隱藏數據將在DOM中顯示並使用CSS .ng-hide {display: none !important;}

JSFiddle: http//jsfiddle.net/WfgXH/3/

這篇文章也可能對您有用,因為它描述了類似的問題: https//stackoverflow.com/a/22886515/1580941

你使用ng-if 它也會進行轉換,不幸的是使用它自己范圍的子范圍,而范圍又是隔離范圍。

以下是Batarang的截圖。 第一個是使用ng-if的代碼。 4是隔離范圍,6是轉換內容。

使用ng-if的范圍

沒有ng-if的相同。 被轉換的內容現在是5,是隔離范圍的兄弟,更重要的是控制器范圍的子代。

沒有ng-if的范圍

在指令中定義scope屬性后,它將成為一個獨立的范圍。 無法訪問外部(在某種程度上,唯一的方法是丑陋且應該避免),除了通過scope屬性傳遞給它的東西。

你需要將它們傳遞給指令:更新你的jsfiddle

<requires-authorization role='Admin' data-auth-value='authValue' data-unauth-value='unAuthValue'>
  <div>Inside directive. For Admin eyes only</div>
  <p>{{authValue}}</p>
</requires-authorization>

// your directive scope
scope: {
  role: '@',
  authValue: '=',
  unauthValue: '='
}

或者創建一個服務/工廠作為中間人進行溝通。

暫無
暫無

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

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