在自定义指令

时间:2016-11-14 10:02:58

标签: angularjs angularjs-directive material-design angular-material

为什么我不能在自定义指令中包装md-list-item?

原始html

 <md-list class="md-dense">
        <md-list-item  ng-repeat="user in items"> 
            <img ng-src="{{user.img}}" class="md-avatar"/>
            <span flex>{{user.code}}</span>
            <span flex>{{user.date}}</span>
            <span flex>{{user.destination}}</span>
            <md-divider inset></md-divider>
        </md-list-item>
 </md-list>

,结果是

enter image description here

指令my-user

指令消费者

<md-list class="md-dense">
    <md-list-item  ng-repeat="user in items"> 
       <my-user ng-model=user></my-user>
       <md-divider inset></md-divider>
    </md-list-item>
</md-list>

my_user.directive.js

angular.module("monitorApp")
.directive('myUser',[function(){
    return {
        restrict:'E',
        scope:{
            ngModel:'='
        },
        templateUrl:'/src/my_user.html',
        link:function(scope){
            scope.$watch('ngModel',function(){
                scope.user = scope.ngModel ? scope.ngModel : {};
            });

        }
    };
}]);

指令模板my_user.html

<div>
  <img ng-src="{{user.img}}" class="md-avatar"/>
  <span flex>{{user.code}}</span>
  <span flex>{{user.date}}</span>
  <span flex>{{user.destination}}</span>
</div>

将导致

enter image description here

因为yuo可以看到物品没有正确呈现。 也许因为使用该指令,md-list-item不是md-list的直接子代,但它们由directive标记和div标记包装。 我试图在我的指令中使用replace:true或者使用带有限制的指令:&#39; A&#39;但没有成功。

希望有人可以帮助我

1 个答案:

答案 0 :(得分:1)

您应该将md-list-item添加到指令模板 - CodePen

标记

<div ng-controller="AppCtrl" ng-cloak="" ng-app="MyApp">
  <md-list class="md-dense">
    <my-user ng-repeat="user in items" ng-model=user></my-user>
    <md-divider inset></md-divider>
  </md-list>

  <script type="text/ng-template" id="my_user.html">
    <md-list-item>
      <img ng-src="{{user.img}}" class="md-avatar"/>
      <span flex>{{user.code}}</span>
      <span flex>{{user.date}}</span>
      <span flex>{{user.destination}}</span>
    </md-list-item>
  </script>
</div>

JS

angular.module('MyApp',['ngMaterial'])

  .directive('myUser',[function(){
    return {
      restrict:'E',
      scope:{
        ngModel:'='
      },
      templateUrl:'my_user.html',
      link:function(scope){
        scope.$watch('ngModel',function(){
          scope.user = scope.ngModel ? scope.ngModel : {};
        });
      }
    };
  }])

  .controller('AppCtrl', function($scope) {
    $scope.items = [
      {code: 1, date: "14/11/16", destination: "Camden"},
      {code: 2, date: "14/11/16", destination: "Camden"},
      {code: 3, date: "14/11/16", destination: "Camden"}
    ];
  });
相关问题