angularJS ng-repeat中的directive 动态加载template

有个需求,想实现一个html组件,传入不同的typeId,渲染出不同的表单元素。

    <div ng-repeat="field in vm.data">
       <magic-field type="{{field.fieldTypeId}}"></magic-field>
    </div>

如当属性type的值为1,输出input元素,type=2输出textarea

也就是说我们要在directive中根据属性获得不同的template。

刚开始我的设想是利用 templateUrl 可以接收一个方法:

    .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;
            },
        }
    })

但是此路不通。

如果属性值 type=1 是明确的可以编译成功,但是我们的directive是放到了ng-repeat中,属性值不固定,{{field.fieldTypeId}}没有编译。

打印attr,type值为未编译的 {{field.fieldTypeId}}。

原因是执行顺序问题,是先加载template内容然后执行link。

解决办法:使用ng-include

完整代码:

    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;
               }
            }
        }
    })
原文地址:https://www.cnblogs.com/mafeifan/p/5814500.html