$ scope不适用于指令中的已编译模板

时间:2015-01-20 10:46:13

标签: angularjs angularjs-directive

对于包含多个模板的弹出窗口,我有以下指令:

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);
            });
          });
        }
      }
    });


我已将visibility标记固定到$rootScope(使css可以看到弹出窗口)以及数据对象中的索引和项目。弹出模板如下所示:

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

该指令加载弹出模板并将其附加到我的mainElement,但不适用范围。因此弹出窗口不会出现,也没有数据绑定到它。

1 个答案:

答案 0 :(得分:3)

你需要传递$ scope。$ parent而不是$ scope进行编译。因为你在孩子的范围内。

相关问题