javascript - Angular : Directive transcluded scope lost

标签 javascript angularjs angularjs-directive angularjs-scope

我正在构建一个指令,我正在调用“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);
    }
  };
});

这行得通,但是指令中包含的内容失去了它的范围,特别是它所在 View 的 Controller 的范围。我忽略了什么?

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

笨蛋: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

关于javascript - Angular : Directive transcluded scope lost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23201078/

相关文章:

javascript - JS : For loop continues to iterate after condition is false

除非清除模型,否则在指令内更新模型时,Angularjs 表单 $error 不会更新

javascript - 如何使用 javascript 设置背景颜色和边框

javascript - 将内容插入到第一个选择器

angularjs - 从文件加载 $templateCache

javascript - 如何使用 Angular 在 config.route.js 中传递多个参数?

javascript - 自定义 $compile 指令仅有时适用于同一范围

javascript - AngularJS 自定义指令不使用所选文件更新模型

javascript - 从 javascript 接收字符串时 phpexplode() 不起作用

javascript - Antd 4.0.0 : How to use form. getFieldValue() 和所有表单的 API 为 `const [form] = Form.useForm` ?