ng-include用于指令内的text / ng-template

时间:2014-09-30 23:00:01

标签: javascript angularjs

我想将我的指令模板与主html文件一起存储。为了做到这一点,我想用ng-include加载模板。我知道这种模式适用于Angular 1.1.5,但我无法在Angular 1.2.5中使用它。

以下是HTML代码:

<div ng-app="app">
     <script type="text/ng-template" id="tabs">
        <div class="tabbable">
          <ul class="nav nav-tabs">
            <li ng-repeat="pane in panes" ng-class="{active:pane.selected}">+
              <a href="" ng-click="select(pane)">{{pane.title}}</a>
            </li>
          </ul>
          <div class="tab-content" ng-transclude></div>
        </div>
    </script>
  <tabs>
    <pane title="Localization">
      Date: {{ '2012-04-01' | date:'fullDate' }} <br>
      Currency: {{ 123456 | currency }} <br>
      Number: {{ 98765.4321 | number }} <br>
    </pane>
    <pane title="Pluralization">
      <div ng-controller="BeerCounter">
        <div ng-repeat="beerCount in beers">
          <ng-pluralize count="beerCount" when="beerForms"></ng-pluralize>
        </div>
      </div>
    </pane>
  </tabs>
</div>

和javascript代码:

angular.module('components', [])

  .directive('tabs', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {},
      controller: function($scope, $element) {
        var panes = $scope.panes = [];

        $scope.select = function(pane) {
          angular.forEach(panes, function(pane) {
            pane.selected = false;
          });
          pane.selected = true;
        }

        this.addPane = function(pane) {
          if (panes.length == 0) $scope.select(pane);
          panes.push(pane);
        }
      },
      template:
        '<div ng-include="\'tabs\'"></div>',
      replace: true
    };
  })

  .directive('pane', function() {
    return {
      require: '^tabs',
      restrict: 'E',
      transclude: true,
      scope: { title: '@' },
      link: function(scope, element, attrs, tabsCtrl) {
        tabsCtrl.addPane(scope);
      },
      template:
        '<div class="tab-pane" ng-class="{active: selected}" ng-transclude>' +
        '</div>',
      replace: true
    };
  })

angular.module('app', ['components'])

.controller('BeerCounter', function($scope, $locale) {
  $scope.beers = [0, 1, 2, 3, 4, 5, 6];
  if ($locale.id == 'en-us') {
    $scope.beerForms = {
      0: 'no beers',
      one: '{} beer',
      other: '{} beers'
    };
  } else {
    $scope.beerForms = {
      0: 'žiadne pivo',
      one: '{} pivo',
      few: '{} pivá',
      other: '{} pív'
    };
  }
});

以下是代码:http://jsfiddle.net/sfdwhhLt/1/

0 个答案:

没有答案