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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM