Home Isolated scope on template appended to element parent
Reply: 1

Isolated scope on template appended to element parent

Alexandre D.
1#
Alexandre D. Published in 2018-01-12 15:28:05Z

I have the following directive:

app.directive("mydirective", ['$compile', function($compile) {
    function link(scope, element, attrs, ctrl, $transclude) {
        var actionBtnHTML = `<button type="submit" ng-show="show"></button>`;

        element.parent().append(actionBtnHTML);

        $compile(element)(scope);
    }

    return {
        restrict: 'A',
        scope: {},
        link: link,
        controller: ['$scope', function MyDirectiveController($scope) {
            $scope.show = true;
        }]
}]);

My directive simply adds a button after the HTML tag with the mydirective attribute.

I want that the added HTML has the same scope as the directive (ie. the new isolated scope). But it is not the case in this configuration. I guess this is because the added HTML is outside the directive HTML tag.

Whence my question, how can I apply the isolated scope of my directive on the template appended to parent element?

Alex K
2#
Alex K Reply to 2018-01-12 16:42:07Z

You can use ngTransclude to insert the extra HTML content while keeping the same scope of the directive.

directive("mydirective", ['$compile', function($compile) {

  return {
    restrict: 'A',
    scope: {},
    controller: ['$scope', function MyDirectiveController($scope) {
      $scope.show = true;
    }],
    transclude: true,
    template: '<ng-transclude></ng-transclude>' +
      ' <button type="submit" ng-show="show">Submit!</button>'
  }
}])

Here's a demo fiddle for your directive!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308789 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO