• 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;
                   }
                }
            }
        })
  • 相关阅读:
    免密码远程登录和远程操作
    1、linux网络服务实验 用PuTTY连接Linux
    巧用CAS解决数据一致性问题
    第一天
    图像处理02
    图像处理01
    Poem 01(转)
    CS229 Lecture 01
    日本語1
    latex测试
  • 原文地址:https://www.cnblogs.com/mafeifan/p/5814500.html
Copyright © 2020-2023  润新知