码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-08-28 11:05:00      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:

需求,想实现一个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 除了可以接收地址字符串,如‘tpl/demo.html‘。

也可以接收一个方法:

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

 

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

标签:

原文地址:http://www.cnblogs.com/mafeifan/p/5814500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!