javascript - 如何使用嵌套指令保留范围?

标签 javascript angularjs scope nested transclusion

我的目标是为可重复使用的轻型 UI 元素创建一组灵活的指令。每个都有一个独立的范围,其中许多都包含内容。我希望每个指令都是一个黑盒子——理想情况下,用户在编写要嵌入的内容时不需要知道它是否在内部嵌套了另一个指令。

根据Angular guide to directives :

The transclude option changes the way scopes are nested. It makes it so that the contents of a transcluded directive have whatever scope is outside the directive, rather than whatever scope is on the inside. In doing so, it gives the contents access to the outside scope.

我发现在使用单个指令时,它的工作原理与描述的一样。但是,如果在该指令中嵌套了另一个也包含内容的指令,则包含的内容将在外部指令的范围内解析,而不是在外部指令的范围内解析。这是一个问题,因为它使用户无法知道他们的嵌入内容将在什么范围内得到解析!

例如:( fiddle )

.controller('main', function ($scope) {
    $scope.value = '"main"';
    $scope.expected = $scope.value;
})

.directive('outer', function () {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: { expected:'=' },
        controller: function ($scope) {
            $scope.value = '"outer"';
        },
        template: '<div><inner expected="expected"><span ng-transclude></span></inner></div>'
    };
})

.directive('inner', function () {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: { expected:'=' },
        controller: function ($scope) {
            $scope.value = '"inner"';
        },
        template: '<div><span>\'value\' is expected to be resolved in scope {{expected}}, and is resolved in scope </span><span ng-transclude></span></div>'
    };
})

和 HTML:

<div ng-controller="main">
    <inner expected="value">
        <span>{{value}}</span>
    </inner>
    <hr/>
    <outer expected="value">
        <span>{{value}}</span>
    </outer>
</div>

<inner></inner>里面元素 {{value}}在父范围内被评估为“主要”(如预期的那样)。但是,在 <outer></outer> 里面元素 {{value}}outer 的隔离范围内进行评估作为“外部”(不是预期的)。这样,指令的模板可以影响解析嵌入内容的范围!

有什么办法可以解决这个问题吗?

最佳答案

这真的很糟糕! Angular 只在隔离范围内调用一个父级,如果它没有找到它需要的东西,它就会停止寻找。要解决这个问题,您可以像这样手动调用作用域的父级:

controller: function ($scope) {
    $scope.value = $scope.$parent.value || '"outer"';
}

这将“让”他看得更远。

关于javascript - 如何使用嵌套指令保留范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21488803/

相关文章:

javascript - 仅当字符串不以某些字符开头时才获取字符串吗?

Javascript 奇怪的行为,异步问题?

javascript - 如何在 Angular 中模拟 $http 成功?

c# - 在循环内部或外部声明一个变量更好吗?

javascript - 以同样的形式上传图片和文字

javascript - Angular $watch 对象并获取属性名称

javascript - 独特的过滤器在 Angular.js 中无法正常工作

c++ - 在父类(super class)中定义但在子类 : accessing subclass attributes? 中实现的方法

database - 如何将数据库连接传递给我的 http 处理程序?

javascript - jQuery隐藏当前div并显示下一个