1

Say I have some html in angular :

 <input type='text' ng-model='stuff' /> {{stuff}}
 <button class="primary" ng-click='dothestuff()'>Do the stuff</button>

With the following in the controller :

$scope.stuff = 'arf';
$scope.dothestuff = function () {
    $window.alert($scope.stuff);    
};

This code will take I enter in the input and output it when I hit the button.

All works well.


But now I want to create a directive that wraps the elements in a div (so it shows in a dark grey background).

I create a directive that will transclude the elements and wrap them with the div:

testapp.directive('wrapper', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: false,
        transclude: true,
        template: '<div style="background:#666"><div ng-transclude></div></div>'
    };
});

But of course, this directive will then create a new scope for the transcluded elements. The input element no longer refers to the stuff property that will get output when hitting the button.

I can make it work by referencing $parent as :

 <input type='text' ng-model='$parent.stuff' /> {{stuff}}

However, I would prefer not to. I want to leave the html as untouched as possible when wrapping with my new directive.

How can I make the transcluded elements refer directly to the parent scope?

Here is a jsFiddle with the problem.

Mongus Pong
  • 11,337
  • 9
  • 44
  • 72

1 Answers1

6

Instead of trying to make the transcluded elements refer to the parent scope, it is better to use object properties:

$scope.obj = {stuff: 'arf'};

fiddle

Since the transcluded scope prototypically inherits from the parent scope, the transcluded scope has access to all of the parent scope properties. By using object properties, "writes" go to the parent scope properties. (When using primitives, "writes" create new properties on the child transcluded scope, which hide/shadow the parent scope properties of the same name.)

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • So there is no way to actually make the transcluded scope be the current parent scope? This is a good work around though, and probably a good standard to follow - wrapping all data of a scope into an object. – Mongus Pong Jul 29 '13 at 20:58
  • @MongusPong, I'm not aware of any way to make the transcluded scope be the parent scope. – Mark Rajcok Jul 30 '13 at 12:44