从已转换的内容访问控制器范围

时间:2013-10-08 18:23:53

标签: angularjs custom-component transclusion

我正在开发我的第一个Angular应用程序(是的!)。我正在尝试使用一个通用模态组件,它可以声明标题,自定义内容和任意数量的操作按钮。后面的设置如下,然后我的问题在底部。

以下是我要使用该指令的方法。

<!-- in app/views/library/index.html -->
<!-- outside <modal> #i_work works great -->
<select id="i_work">
  <option value="{{libraryType.id}}" ng-repeat="libraryType in libraryTypes">{{libraryType.name}}</option>
</select>

<modal id="library_new" title="My Custom Title">
  <form>
    <!-- inside <modal> #i_dont_work doesn't work -->
    <select id="i_dont_work">
      <option value="{{libraryType.id}}" ng-repeat="libraryType in libraryTypes">{{libraryType.name}}</option>
    </select>
  </form>

  <modal-buttons>
    <!-- [toggle-modal] is another directive that shows/hides a given <modal> -->
    <button type="button" toggle-modal="library_new">cancel</button>

    <button type="submit" ng-click="addLibrary()">save</button>
  </modal-buttons>
</modal>

这是指令代码:

// in app/scripts/directives/modal.js
'use strict';
angular.module('sampleAngularApp')
  .directive('modal', [function () {
    return {
      templateUrl: '/scripts/directives/modal.html',
      restrict: 'E',
      transclude: true,
      link: {
        pre: function preLink(scope, element, attrs) {
          scope.id = attrs.id;
          scope.title = attrs.title;
        },
        post: function preLink(scope, element, attrs) {
          // hacky-hack to transclude specific content into other targets.
          //   bound event handlers should be preserved (as implemented they are).
          //   this actually works
          var buttonWrap = element.find('modal-buttons');
          buttonWrap.children().each(function (index, button) {
            element.find('.modal-footer').append(button);
          });
          buttonWrap.remove();
        }
      }
    };
  }]);

...和指令模板:

<!-- in app/scripts/directives/modal.html -->
<div class="modal" role="dialog">
  <div class="modal-header">
    <span class="title">{{title}}</span>
    <button type="button" class="close" toggle-modal="{{id}}">close</button>
  </div>

  <!-- the contents of .modal-body should be everything inside <modal> above, -->
  <!--   except for <modal-buttons> -->
  <div class="modal-body" ng-transclude />

  <!-- the contents of .modal-footer should be the contents of <modal-buttons> -->
  <div class="modal-footer" />
</div>

问题:

1)考虑上面控制器视图中的<select>元素。 #i_work正确呈现<option>就好了。 #i_dont_work呈现<select>,但没有<option>libraryTypes似乎不在<modal>范围内。为什么会这样,我该如何解决?

2)有没有更好的方法将特定内容转换为多个目标? Google的Polymer项目为<content />提供了一个可选的[select]属性,以提供多个插入目标。 Angular有这样的东西吗? (有关详细信息,请参阅Polymer's website。)

0 个答案:

没有答案