Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Transclude in scope #14303

Open
Open
@wytrych

Description

@wytrych

I have come to use this pattern quite often:

An isolated scope directive with transclusion providing some $scope methods and properties with a default template that has UI elements using these methods.

For example:

module.directive('myDirective',
        function () {
            return {
                restrict: 'A',
                transclude: true,
                scope: {},
                templateUrl: 'templates/my-directive.html',
                link: function ($scope, $element, $attrs, $ctrl, $transclude) {
                     $scope.myMethod = function() {
                         ...
                     }
                     $scope.myProperty = 'example';
                }
            };
        }
);

In my template I have:

<div>
    <div transclude-in-scope>
        <button type="button" ng-click="myMethod()">Go</button>
    </div>
    <div>
          Some default content
    </div>
</div>

I would like to be able to replace the button for another element but still have access to the isolated scope. I figured I can do it this way, in the link function:

                    $transclude($scope, function ($clone, $scope) {
                        if ($clone.length) {
                            $element.find('[transclude-in-scope]').replaceWith($clone);
                        }
                    });

Then I can use it like so:

<div my-directive>
    <button type="button" class="some-specific-class" ng-click="myMethod()">Please click</button>
</div>

It's basically like using ng-controller but with a default template. Considering the new transclude-slot functionality I think it would be very useful to be able to have a possibility to tell a directive that I want to transclude in the isolated scope. This way I can change some of the elements on the template, without having to ovveride the whole thing.

Do you think this is something worth putting in Angular? I'd be happy to submit a PR.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions