本文介绍了角度的嵌入和范围:为什么这不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

angular.module('transclude', []).directive('窗格', 函数(){返回 {限制:'E',转置:真实,范围:{标题:'@'},模板:'

'+'<div>独立范围内的标题:{{title}}</div>'+'<div ng-transclude></div>'+'</div>'};});

plunker 在这里:http://plnkr.co/edit/yRHcNGjQAq1NHDTuwXku

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

解决方案

被嵌入元素的作用域不是指令的子作用域,而是同级作用域.文档是这样说的:

在典型的设置中,widget 创建一个隔离作用域,但嵌入不是一个子级,而是隔离作用域的一个兄弟.

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

.directive('pane', function () {返回 {限制:'E',转置:真实,范围: {标题: '@'},模板:'

'+'<div>独立范围内的标题:{{title}}</div>'+'<div ng-transclude></div>'+'</div>',链接:函数(范围、元素、属性){scope.$$nextSibling.title = attrs.title;}};});

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

I have a very simple setup:

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

and

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

The plunker is here: http://plnkr.co/edit/yRHcNGjQAq1NHDTuwXku

The transclusion itself is working but the {{title}} only gets replaced in the directive's template.
The {{title}} inside the transcluded element however stays empty even though the directive has a variable title in its scope. Why is that?

解决方案

The scope of the transcluded element is not a child scope of the directive but a sibling one. This is what documentation says:

The simplest solution in this case how you can access transcuded scope is like this:

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

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

这篇关于角度的嵌入和范围:为什么这不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 02:49