Gordian
Gordian

Reputation: 258

$scope doesn't apply to compiled template in directive

I have the following directive for a popup with multiple templates:

app.directive('popup', function ($http, $rootScope, $templateCache, $compile, $parse, Popup) {
      return {
        link: function ($scope, $element, $attrs) {
          $element.bind('click', function () {
            var data = {
              index: $attrs.index
            }
            $http.get('/partial/' +  $attrs.popup + '.html', {cache: $templateCache}).success(function (tplContent) {
              var mainElement = angular.element(document.getElementById('main'));
             mainElement.append($compile(tplContent)($scope));
              Popup.show(data);
            });
          });
        }
      }
    });


I've pinned a visibility flag to $rootScope (to make the popup visible by css) along with index and item that came in data object. and the popup template looks like this:

<section class="popup" ng-class="{'show': popup.visibility}">
  <h1>{{data[popup.index].title}}<h1>
  <p>{{data[popup.index].message}}<p>
</section>

The directive loads the popup template and appends it to my mainElement, but doesn't apply scope to. so popup doesn't appear and no data is bound to it.

Upvotes: 2

Views: 92

Answers (1)

Reyraa
Reyraa

Reputation: 4294

you need to pass $scope.$parent instead of $scope for compiling. because you are in the child $scope.

Upvotes: 3

Related Questions