有个需求,想实现一个html组件,传入不一样的typeId,渲染出不一样的表单元素。html
<div ng-repeat="field in vm.data"> <magic-field type="{{field.fieldTypeId}}"></magic-field> </div>
如当属性type的值为1,输出input元素,type=2输出textareaangularjs
也就是说咱们要在directive中根据属性得到不一样的template。api
刚开始个人设想是利用 templateUrl 能够接收一个方法:app
.directive('magicField', function(){ return { templateUrl: function(elem, attr){ if(attr.type == 1) { template = 'tpl/mgfield/input.html' } if(attr.type == 2) { template = 'tpl/mgfield/textarea.html' } return template; }, } })
可是此路不通。this
若是属性值 type=1 是明确的能够编译成功,可是咱们的directive是放到了ng-repeat中,属性值不固定,{{field.fieldTypeId}}没有编译。spa
打印attr,type值为未编译的 {{field.fieldTypeId}}。code
缘由是执行顺序问题,是先加载template内容而后执行link。htm
解决办法:使用ng-includeblog
完整代码:element
angular.module("app", []) .controller("DemoCtrl", ['$scope', function($scope){ var vm = this; vm.data = [ { fieldTypeId: 1, title: 'first name' }, { fieldTypeId: 2, title: 'this is text area' } ] }]) .directive('magicField', function(){ return { template: '<div ng-include="getContentUrl()"></div>', replace: true, //transclude: true, link: function($scope, $element, $attr){ $scope.getContentUrl = function() { if($attr.type == 1) { template = 'tpl/mgfield/input.html' } if($attr.type == 2) { template = 'tpl/mgfield/textarea.html' } return template; } } } })