本文介绍了AngularJS:指令嵌入范围丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个指令,我正在调用requires-authorization"来包装一个 ng-if 指令.我想按如下方式使用它:

I’m building a directive, I’m calling ‘requires-authorization’ to wrap an ng-if directive. I’d like to use it as follows:

<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);
    }
  };
});

这是可行的,但是指令中包含的内容失去了它的范围,特别是它所在的视图的控制器的范围.我忽略了什么?

This works, but the content contained within the directive loses its scope, specifically the scope of the controller of the view it's found within. What am I overlooking?

jsfiddle 供参考:http://jsfiddle.net/HbAmG/8/请注意 auth 值如何不在指令内部显示,但在指令外部可用.

jsfiddle for reference: http://jsfiddle.net/HbAmG/8/ Notice how the auth value isn't displayed inside the directive, but is available outside directive.

推荐答案

ng-ifng-transclude 指令都在您的指令中执行嵌入.在这种情况下,内置的嵌入机制无法正常工作,您应该自己实现 ngIf 以使其按预期工作:

Both ng-if and ng-transclude directives perform transclusion in your directive. In this case build-in transclude mechanism does not work fine and you should implement ngIf of yourself to make it work as expected:

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;}.

If ng-show is an option for you to use instead of ng-if it may be a very simple workaround as well. The only side effect is that hidden data will be presented in the DOM and hidden using CSS .ng-hide {display: none !important;}.

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

这篇文章也可能对您有用,因为它描述了类似的问题:https://stackoverflow.com/a/22886515/1580941

This post may also be useful for you since it describes the similar issue: https://stackoverflow.com/a/22886515/1580941

这篇关于AngularJS:指令嵌入范围丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:32