重复Angular中的转换 - 访问当前项目的最佳实践?

Law*_*eld 5 angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

我写了以下指令:

transclude: true,
scope: { items: '=' }
...
<div class="row" ng-repeat="item in items">
  <div class="col-xs-9">
    <ng-transclude></ng-transclude>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

使用此指令时,执行以下操作是合法/良好的做法吗?

cakes = [ { name: 'blueberry cheesecake', color: 'blue' }, { name: 'rocky road', color: 'mostly brown' } ]
...
<custom-list items="cakes">
  <h5>{{$parent.item.name}}</h5>
</custom-list>
Run Code Online (Sandbox Code Playgroud)

我特别谈到$parent.方面.

Law*_*eld 2

Angular 已经认识到更灵活的做法ng-transclude是有益的:

https://github.com/angular/angular.js/issues/5489

建议的解决方法之一是定义您自己的覆盖,以便ng-transclude您可以执行以下操作:

<div ng-transclude="sibling"></div> <!-- Original behaviour -->
<div ng-transclude="parent"></div> <!-- Takes from where transclusion happens -->
<div ng-transclude="child"></div> <!-- Takes from where transclusion happens, but creates a new child scope -->
Run Code Online (Sandbox Code Playgroud)

定制来源ng-transclude

.config(function($provide){
    $provide.decorator('ngTranscludeDirective', ['$delegate', function($delegate) {
        // Remove the original directive
        $delegate.shift();
        return $delegate;
    }]);
})

.directive( 'ngTransclude', function() {
  return {
    restrict: 'EAC',
    link: function( $scope, $element, $attrs, controller, $transclude ) {
      if (!$transclude) {
        throw minErr('ngTransclude')('orphan',
         'Illegal use of ngTransclude directive in the template! ' +
         'No parent directive that requires a transclusion found. ' +
         'Element: {0}',
         startingTag($element));
      }

      var iScopeType = $attrs['ngTransclude'] || 'sibling';

      switch ( iScopeType ) {
        case 'sibling':
          $transclude( function( clone ) {
            $element.empty();
            $element.append( clone );
          });
          break;
        case 'parent':
          $transclude( $scope, function( clone ) {
            $element.empty();
            $element.append( clone );
          });
          break;
        case 'child':
          var iChildScope = $scope.$new();
          $transclude( iChildScope, function( clone ) {
            $element.empty();
            $element.append( clone );
            $element.on( '$destroy', function() {
              iChildScope.$destroy();
            });            
          });
          break;
      }
    }
  }
})
Run Code Online (Sandbox Code Playgroud)