Gianpolo Gianpolo - 24 days ago 17
AngularJS Question

wrap md-list-item in custom directive

why i can't wrap an md-list-item in a custom directive ?

Original 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>


and the result is

enter image description here

Directive my-user



Directive consumer



<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 : {};
});

}
};
}]);


directive template 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>


will result in

enter image description here

As yuo can see the items are not rendered right.
Maybe because using the directive the md-list-item are not directly child of md-list but they are wrapped by the directive tag and the div tag.
I tried to use the replace:true in my directive or use the directive with restricted:'A' but without success.

Hope can someone help me

Answer

You should add md-list-item to your directive template - CodePen

Markup

<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"}
    ];
  });