【问题标题】:Scope generation in directive template does't work with transclude指令模板中的范围生成不适用于 transclude
【发布时间】:2014-03-16 07:21:09
【问题描述】:

如何在Angularjs中定义一个获取参数并用ngIf或ngRepeat嵌入子元素的指令?

可以在此处找到该问题的完整演示 - http://jsfiddle.net/2aa47/4/。这是 HTML:

<div ng-controller='myController'>
    <my-directive condition="flag">
        Both 'flag' and 'a' are defined on controller's scope.
        Hi. {{a}} -> Nothing is shown after 'Hi'.
    </my-directive>
</div>

还有剧本。在我真正的问题中,我有一个更大的模板,中间有 ngIf。

app.directive('myDirective', function () {
    return {
        restrict: 'E',
        transclude: true,
        scope: { condition: '=condition' },
        template: '<div ng-if="condition" ng-transclude></div>'
    };
});

为了获取参数指令,应该创建一个独立的范围。 ngIf、ngRepeat 和其他类似指令都将创建一个继承自该隔离范围的范围。然后被嵌入的元素将获得后者的作用域兄弟,这意味着直接在指令的孤立元素之下:

Controller's scope
  Directive's isolated scope
    Scope created by ngIf
    Element transcluded by directive. Should be directly under controller's scope

现在指令内的嵌入元素无法访问控制器的范围。如何减轻这种情况?

作为参考,Angular 项目中有这样一个问题 - https://github.com/angular/angular.js/issues/1809

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    我已经为此here 找到了解决方法。

    通过将setTransscope 注入到您的指令中并在链接阶段调用它,正确的范围被标记为transcluding。不要在模板中使用ng-transclude 指令,而应使用ng-transscope 指令,这会恢复之前标记的范围。

    指令

    myApp.directive('myDirective', function(setTransscope) {
      return {
        scope: {
          display: "="
        },
        transclude: true,   // required
        restrict: 'EA',
        templateUrl: 'my-template.html',
        link: setTransscope
    
        /* ... or call within your own link function:
        link: function($scope, $element) {
          setTransscope($scope, $element);
    
          // ...
          // Other stuff
          // ...
        } */
    
      };
    });
    

    模板

    <div ng-if="display">
      <div ng-transscope></div>
    </div>
    

    【讨论】:

    • 非常感谢。已测试 - jsfiddle.net/2aa47/10。我只遇到了打电话给$element.empty(); 的问题。出于某种原因,empty 被低估了。没有它,指令显然有效。而且范围转储器似乎是一个强大而简单的调试工具。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多