angularjs:directive创建两个子范围(不是隔离范围)?以及如何获得元素的范围?

zx_*_*ing 5 scope directive angularjs

我正在编写我的angularjs指令,其定义如下:

return {
    restrict: 'EA',
    link: link,
    scope: true,
    transclude: true,
    replace: true,
    controller: controller,
    template: '<div class="wizard">' +
        '<div ng-transclude></div>' +
        '</div>'
};
Run Code Online (Sandbox Code Playgroud)

我注意到创建了两个范围:

< Scope (003)  --- parent scope of directive
    < Scope (004)  --- controller scope of directive which I think is child scope created by 'scope=true'. all my functions, properites defined in controller show up in this scope
    < Scope (005)  --- transclude scope which is empty
Run Code Online (Sandbox Code Playgroud)

从文档我期望只创建一个子范围,因为'scope = true'不会创建一个孤立的范围.这导致所有被'ng-transclude'替换的元素实际上继承了Scope(005)并且无法访问我在控制器中定义的函数/属性,因为它们在Scope(004)中,它是Scope(005)的兄弟.

我不知道出了什么问题,有人可以在这里点灯吗?

当使用Chrome调试器观察我的元素时,我注意到这些元素是由"ng-scope"类添加的,但是,如何将"ng-scope"与batarang控制台中显示的范围相匹配?比如show ng-scope的id.

谢谢

Mar*_*cok 15

scope: true将创建一个原型继承自控制器范围的新子范围 - 这是范围004.

scope: { ... } 将创建一个新的子范围,不会从控制器范围原型继承.

无论哪种方式,都会创建一个新的子范围.

此外,因为您正在使用transclude: true,所以创建了另一个(已转换的)子范围005.Transcluded范围始终从控制器范围原型继承.

正如您已经发现的那样,您在指令范围(即指令内)中定义的属性和函数对视图不可用,因为视图使用了被转换的范围.

在此输入图像描述

上图基于以下代码:

app.directive('myDirective', function() {
    return {
        restrict: 'EA',
        //link: link,
        scope: true,
        transclude: true,
        replace: true,
        controller: function($scope) {
            $scope.dirProp1 = "dirProp1";
            $scope.dirFunc = function() {}
        },
        template: '<div class="wizard">' +
            '<div ng-transclude></div>' +
            '</div>'
    };
});
Run Code Online (Sandbox Code Playgroud)

function MyCtrl($scope) {
    $scope.parentCtrlProp1 = 'ParentCtrlProp1';
}
Run Code Online (Sandbox Code Playgroud)

因此,从图中可以看出,转换范围(因此转换内容)只能通过原型链访问控制器范围(003)上定义的属性和函数.


如何将"ng-scope"与batarang控制台中显示的范围相匹配?比如show ng-scope的id.

我不知道有什么方法可以做到这一点(这就是为什么我写了一个工具来绘制我自己的图片).