zoukankan      html  css  js  c++  java
  • 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;
                   }
                }
            }
        })
  • 相关阅读:
    编程爱好者论坛第六次编程比赛题目
    google china code jam round2 div1 1000分题
    ogl2dlibsdl cvs repository @ cosoft
    偶尔也提一个游戏点子:宇宙碰撞
    今天看到一些笑话...
    google china code jam入围赛的一个题
    用Regular expression寻找源代码中的汉字字符串
    生成函数理论初步
    Komodo 的中文支持
    “豪华版”的USB延长线
  • 原文地址:https://www.cnblogs.com/mafeifan/p/5814500.html
Copyright © 2011-2022 走看看