angular : direative : scope | 指令scope和transclude的关系

今天记入的是指令的scope和transclude关系

 

a 和 b 都是指令

<div a>

  <div b></div>

</div>

a transclude了b,b的$$prevSibling是a,而a的$$prevSibling不是b

<div a>
    <div ng-transclude="">
        <div b></div>
    </div>
</div>
angular.module("Member", []).
            directive("a", [function () {
                return {
                    restrict: "A",
                    transclude : true,
                    template :"<div ng-transclude></div>",
                    link: function ($scope) {
                        console.log("a");
                        console.log($scope);
                    },
                    scope : true,
                }
            }]).
            directive("b", [function () {
                return {
                    restrict: "A",
                    link: function ($scope) {
                        console.log("b");
                        console.log($scope);
                    }
                }
            }])

问题来了:为什么使用ng-transclude会自动创建一个新的scope?而且是sibling?那我不会回答,但是如果我要继承指令a的scope该怎么办?

解决方案:https://github.com/angular/angular.js/issues/1809

angular.module("my").directive('myTransclude', function() {
    return {
        compile: function(tElement, tAttrs, transclude) {
            return function(scope, iElement, iAttrs) {
                transclude(scope.$new(), function(clone) {
                    iElement.append(clone);
                });
            };
        }
    };
});

那原本的ng-transclude替换成my-transclude就能解决sibling问题。

如果你需要指令b的scope不是自己的,你可以删除掉$new()

如果你需要指令a是隔离的,同时指令b的scope要是rootscope,你就用回ng-transclude吧~

 

 

 

 

原文地址:https://www.cnblogs.com/stooges/p/3934465.html