javascript - Angular : Why is this not working? 中的包含和范围

标签 javascript angularjs angularjs-scope transclusion

我有一个非常简单的设置:

<pane title="mytitle">Title in parent (transcluded): {{title}}</pane>

angular.module('transclude', [])
 .directive('pane', function(){
    return {
      restrict: 'E',
      transclude: true,
      scope: { title:'@' },
      template: '<div>' +
                  '<div>Title in isolated scope: {{title}}</div>' +
                  '<div ng-transclude></div>' +
                '</div>'
    };
});

骗子在这里:http://plnkr.co/edit/yRHcNGjQAq1NHDTuwXku

嵌入本身正在工作,但 {{title}} 仅在指令的模板中被替换。
然而,即使指令在其范围内有一个变量 title ,嵌入元素内的 {{title}} 仍然为空。这是为什么?

最佳答案

嵌入元素的范围不是指令的子范围,而是同级范围。文档是这样说的:

In a typical setup the widget creates an isolate scope, but the transclusion is not a child, but a sibling of the isolate scope.

在这种情况下,如何访问转译范围的最简单解决方案如下:

.directive('pane', function () {
    return {
        restrict: 'E',
        transclude: true,
        scope: {
            title: '@'
        },
        template:
            '<div>' +
                '<div>Title in isolated scope: {{title}}</div>' +
                '<div ng-transclude></div>' +
            '</div>',
        link: function (scope, element, attrs) {
            scope.$$nextSibling.title = attrs.title;
        }
    };
});

演示:http://plnkr.co/edit/ouq9B4F2qFPh557708Q1?p=preview

关于javascript - Angular : Why is this not working? 中的包含和范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23027254/

相关文章:

javascript - 如何选择在 Angular 中动态加载的 html 元素?

javascript - 如何将下拉值绑定(bind)到 url,然后使用此 url 获取文本字段中的数据?

javascript - javascript 中的多对多映射对象

angularjs - Jasmine 根据规范的多期望与根据规范的单期望

javascript - 在 Angular 智能表中选择 st-search 不适用于 ng-model

angularjs - 使用angularjs的补丁请求

javascript - php 中的注销限制

javascript - 如何从对象数组中获取项目

javascript - Angular 写入嵌套范围属性

javascript - 如果选中复选框,AngularJS 打印文本