【问题标题】:why can I access the property defined outside the isolated scope?为什么我可以访问隔离范围之外定义的属性?
【发布时间】:2014-07-12 14:41:44
【问题描述】:

我有以下 HTML:

<ng-view>
    <tabset>
        <tab>
            <tab-heading>
                <i class="glyphicon glyphicon-info-sign"></i>
            </tab-heading>
            <div>
                <div>
                    <div>{{selectedWord.translation}}</div>
                </div>
    ...
</ng-view>

以及为视图加载的控制器:

angular.module('app').controller('SampleController', function ($scope) {
    $scope.selectedWord = {translation: '[te]'};
}

ng-view 指令创建了一个新作用域,我认为它会作为参数注入到SampleController 构造函数中。

tabset 创建自己的隔离作用域,因此它不会从ng-view 创建的作用域继承属性。

.directive('tabset', function() {
  return {
    restrict: 'EA',
    transclude: true,
    replace: true,
    scope: {
      type: '@'
    },

每个tab 指令还创建自己的范围,该范围也不是从tabset 指令创建的范围继承的。

.directive('tab', ['$parse', function($parse) {
  return {
    require: '^tabset',
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/tabs/tab.html',
    transclude: true,
    scope: {
      active: '=?',
      heading: '@',
      onSelect: '&select', //This callback is called in contentHeadingTransclude
                          //once it inserts the tab's content into the dom
      onDeselect: '&deselect'
    },

我不明白的是为什么可以从tab 指令创建的范围内访问ng-view 指令创建的范围内定义的属性tab 指令(它本身是独立的范围和前面是 tabset) 创建的隔离范围?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    当指令使用嵌入时,它会为被嵌入的内容创建一个子范围(有时也称为嵌入范围)。当一个指令还定义了一个隔离作用域时,实际上在同一个指令中使用了两个作用域:

    1. 嵌入范围 - 绑定到被嵌入的内容
    2. 隔离范围 - 绑定到您的模板(如果已定义)或可用作指令的私有范围。

    所以selectedWord之所以可以解析,是因为被嵌入的内容是绑定到ngView的嵌入范围的。并且任何指令的包含范围只是一个子范围,它在原型上从其父范围继承。

    任何使用嵌入的指令都是如此:

    示例

    <!-- name defined in parent scope -->
    <div ng-init="name='test'">
        <!-- ng-if creates a child scope for its transcluded contents
           The child scope prototypically inherits scope from its parents -->
        <div ng-if="true">
            <!-- this is the transcluded contents for ng-if -->
            <div> 
                <my-dir-using-isolate-scope>
                   <!-- this is the transcluded contents for 
                        my-dir-using-isolate-scope directive --> 
                   {{ name }} 
                </my-dir-using-isolate-scope>
            </div>
        </div>
    </div>
    

    【讨论】:

    • 谢谢!除了docs.angularjs.org 之外,您还知道什么好的资源,那里有关于嵌入作用域的很好解释吗?
    • transcluded contents 在哪里或如何定义?
    • 每当您在具有指令的元素中包含内容时 - tanscluded 内容。包含范围没有什么特别之处。它只是一个子范围。带有模板的指令将用其模板覆盖转入的内容。但是,您也可以通过在模板中应用 ng-transclude 指令,将嵌入的内容链接到模板中。
    • 非常感谢您的详尽回答!我还发现了this 问题和答案——它与嵌入的内容有什么关系吗?我假设Inside isolated scope directive: {{myProperty}}my-inherit-scope-directive 指令中的一个嵌入内容,因此它可以通过一个嵌入范围访问myProperty
    • 啊,我很聪明 :)))...谢谢! :) 那家伙没有明确说明指令是transcluded,所以我猜它默认设置为true
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    相关资源
    最近更新 更多