在编译的html for directive中使用ng-repeat

时间:2014-08-02 19:45:09

标签: angularjs angularjs-directive

我有两个指令:

window.app.directive('placeholder', function ($compile, $route, $rootScope) {
  return {
    restrict: 'AC',
    link: function (scope, element, attr) {
      // Store the placeholder element for later use
      $rootScope["placeholder_" + attr.placeholder] = element[0];

      // Clear the placeholder when navigating
      $rootScope.$on('$routeChangeSuccess', function (e, a, b) {
        element.html('');
      });
    }
  };
});

window.app.directive('section', function ($compile, $route, $rootScope) {
  return {
    restrict: 'AC',
    link: function (scope, element, attr) {
      // Locate the placeholder element
      var targetElement = $rootScope["placeholder_" + attr.section];

      // Compile the template and bind it to the current scope, and inject it into the placeholder
      $(targetElement).html($compile(element.html())(scope));
      element.html('');
    }
  };
});

我使用它们基本上用一个html替换另一个部分。

如果我有以下html:

<div placeholder="footer"></div>

<div section="footer">
    <ul ng-model="items">
      <li ng-repeat="item in items">&nbsp; {{item.Description}}</li>
    </ul>
  </div>

ng-repeat似乎不起作用。如果我只是在其下方输出{{items}},则显示正常。此外,我知道绑定正在起作用,因为我可以更改项目,它会更新。

最后,如果我将ul移到该部分之外,它可以正常工作。

所以,我的问题是为什么这不起作用(编译ng-repeat inside指令)。

我错过了什么吗?

编辑:

令我困惑的是,我能做到这一点:

<div section="footer">
<!-- This Works -->
  {{items}}
<!-- This also works -->
<input type="text" ng-model="items[0].Description" />
<!-- This doesn't work -->
        <ul ng-model="items">
          <li ng-repeat="item in items">&nbsp; {{item.Description}}</li>
        </ul>
      </div>

1 个答案:

答案 0 :(得分:0)

这不会起作用。它无法从另一个范围评估某些内容,而无需在其范围内对其进行精确复制。如果你想要两个指令进行沟通,请使用require并设置一种方法,如果他们不在父子关系中,他们就可以这样做。

你应该考虑几件事。基本上你正在做的事情叫做transclusion。 Section指令将使用ng-transclude来捕获客户端定义的代码。使用transclusion并且您可以将模板评估为部分范围内的html,然后使用指令通信允许它将HTML块(已经评估)传递给另一个指令。唯一的问题是确保当事情通过绑定发生变化时会发生这种情况。您可能需要对部分中的变量进行一些$ watch监视,以便在事情发生变化时通知占位符。

您可能需要第3个指令,因此允许部分和占位符进行通信。在这个例子中说我有一个名为broadcaster的第三个指令。然后部分和占位符将需要广播公司(即要求:&#39; ^广播公司&#39;),它将为每个指令定义一些接口,以便从部分发送HTML - &gt;占位符。像这样:

<div broadcaster>
   <div placeholder="footer"></div>
   <div section="footer">
      <ul>...transcluded content</ul>
   </div>
</div>
相关问题