溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

angularjs解決方案之 遞歸模板

發(fā)布時間:2020-07-01 17:55:03 來源:網(wǎng)絡 閱讀:1267 作者:愛笑嘚蛋蛋 欄目:開發(fā)技術

手風琴模式的菜單:

    在項目中我們會遇到不知層級的json數(shù)據(jù),需要前端人員去遍歷生成View視圖,這種情況下我們就會用到遞歸方法。

    angularjs中的dom結構也是可以用遞歸的方式去循環(huán)遍歷數(shù)據(jù)。

<ul side-navigation class="nav metismenu" ng-include="'navigations'" id="side-menu">
</ul>
<script id="navigations" type="text/ng-template">
    <li ng-repeat="navs in functionGroups">
		<a href="`navs`.`functionpoint`"><span class="nav-label">`navs`.`name`</span><span ng-if="navs.children.length" class="fa arrow"></span></a>
        <ul ng-if="navs.children.length" ng-include="'navigations'" class="nav nav-second-level" ng-init="functionGroups=navs.children"></ul>
    </li>
</script>

另一種采用指令的方式:(未測試)

angular.module('demo').directive('recursion',function($compile){
 
    function cpl(element, link){
        // Normalize the link parameter
        if(angular.isFunction(link)){
            link = { post: link };
        }
 
        // Break the recursion loop by removing the contents
        var contents = element.contents().remove();
        var compiledContents;
        return {
            pre: (link && link.pre) ? link.pre : null,
            /**
             * Compiles and re-adds the contents
             */
            post: function(scope, element){
                // Compile the contents
                if(!compiledContents){
                    compiledContents = $compile(contents);
                }
                // Re-add the compiled contents to the element
                compiledContents(scope, function(clone){
                    element.append(clone);
                });
 
                // Call the post-linking function, if any
                if(link && link.post){
                    link.post.apply(null, arguments);
                }
            }
        };
    }
    
    return {
        restrict:'A',
        scope: {recursion:'='},
        template: '<li ng-repeat="item in recursion">\
                        <a href="`item`.`cateId`.html">`item`.`cateName`</a>\
                        <ul recursion="item.child">\
                        </ul>\
                    </li>',
        compile: function(element){
 
            return cpl(element, function(scope, iElement, iAttrs, controller, transcludeFn){
                // Define your normal link function here.
                // Alternative: instead of passing a function,
                // you can also pass an object with
                // a 'pre'- and 'post'-link function.
            });
        }
    };
});


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI