7

How to prevent directive with transclude to create new scopes?

This jsfiddle I cant bind anything due to the new scopes illustrated with red borders.

Html:

<div ng-app="components">
    <input ng-model="var">
    <block>
        123
        <input ng-model="var">
    </block>
</div>

JavaScript:

angular.module('components', []).directive('block',function(){
    return{
        scope:false,
        replace:true,
        restrict:"E",
        transclude:true,
        template:'<div class="block" ng-transclude></div>',
        link:function(scope, el, attrs, ctrl){

        }
    }
});

CSS:

.ng-scope{
  border:1px solid red;
    margin:10px;
}

2 Answers 2

7

It is actually expected behavior as stated here (ng-transclude create a child scope): https://github.com/angular/angular.js/issues/1056 and discussed here: https://groups.google.com/forum/#!msg/angular/45jNmQucSCE/hL8x48-JfZIJ

You can workaround this by setting a member on an object in the scope (obj.var) like in this fiddle: http://jsfiddle.net/rdarder/pnSNj/10/

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. I made a more simple example jsfiddle.But is that a bug or is it a feature?
It's normal behavior for child scopes (they inherit by prototype from the parent scope, meaning that you can read from the parent scope, but as soon as you write, it's on the child scope - unless you use the obj on the parent scope workaroud), you could perhaps take a look at the source code of the ng-transclude directive, copy it and make your own with a scope: false option.
The issues comes up again if I start using transclude set as element. Does anyone have any idea why it doesn't work now. Demo: plnkr.co/edit/Bv1kFQtzdVzsasHTUrgf?p=preview
Why does setting a member on an object get around the fact that the nested template has it's own scope?
More clearly, how does the nested template have access to the parent scope without calling $scope.$parent?
|
0

Although this is not recommended by the Angular team, another workaround is to explicitly call the $parent scope within the transcluded portion:

<div ng-app="components">
    <input ng-model="var">
    <block>
        123
        <input ng-model="$parent.var">
    </block>
</div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.