为什么我不能在自定义指令中包装md-list-item?
<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>
,结果是
<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>
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 : {};
});
}
};
}]);
<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>
将导致
因为yuo可以看到物品没有正确呈现。 也许因为使用该指令,md-list-item不是md-list的直接子代,但它们由directive标记和div标记包装。 我试图在我的指令中使用replace:true或者使用带有限制的指令:&#39; A&#39;但没有成功。
希望有人可以帮助我
答案 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"}
];
});