Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

angularjs - Access Parent Scope in Transcluded Directive

I would like to access a parent directive's scope, but I can't seem to get the right combination of settings. Is this possible and is it the right approach?

I really want to avoid putting something like SOME_CONST (which would help me make DOM updates through control flow) in MyCtrl

<div ng-controller="MyCtrl">
    <parent>
        <child></child>
    </parent>
</div>

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.obj = {prop:'foo'};
}

myApp.directive('parent', function() {
    return {
        scope: true,
        transclude: true,
        restrict: 'EA',
        template: '<div ng-transclude><h1>I'm parent {{obj.prop}}<h1></div>',
        link: function(scope, elem, attrs) {
            scope.SOME_CONST = 'someConst';
        }
    }
});

myApp.directive('child', function() {
    return {
        restrict: 'EA',
        template: '<h1>I'm child.... I want to access my parent's stuff, but I can't.  I can access MyCtrlScope though, see <b>{{obj.prop}}</b></h1> how can I access the <b>SOME_CONST</b> value in my parent's link function?  is this even a good idea? {{SOME_CONST}}.  I really don't want to put everything inside the MyCtrl',
    }
});

Please see this fiddle

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With transclude: true and scope: true, the parent directive creates two new scopes: enter image description here

Scope 004 is a result of scope: true, and scope 005 is a result of transclude: true. Since the child directive does not create a new scope, it uses transcluded scope 005. As you can see from the diagram there is no path from scope 005 to scope 004 (except via private property $$prevSibling, which goes in the opposite direction of $$nextSibling -- but don't use those.)

@joakimbl's solution is probably best here, although I think it is more common to define an API on the parent directive's controller, rather than defining properties on this:

controller: function($scope) {
    $scope.SOME_CONST = 'someConst';
    this.getConst = function() {
       return $scope.SOME_CONST;
    }
}

Then in the child directive:

link:function(scope,element,attrs,parentCtrl){
    scope.SOME_CONST = parentCtrl.getConst();
},

This is how the tabs and pane directives work on Angular's home page ("Create Components" example).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...