Angular dynamically compile template.

app.directive('uiWidget', ['$compile', '$http', '$templateCache', function($compile, $http, $templateCache) {
    return {
        restrict: 'E',
        replace: true,
        require: '^ngModel',
        scope: {
            widget: '=ngModel'
        },
        link: function(scope, element, attrs) {
            var templateUrl = getUrlByWtype(scope.widget.wtype);// 通过wtype动态生成对应的templateUrl
            var loader = $http.get(templateUrl, {cache: $templateCache});
            loader.success(function(html){
                element.html(html).show();
            }).then(function() {
                $compile(element.contents())(scope);
            });
        }
    };
    /**
     * 根据wtype,加载对应的默认模板
     */
    function getUrlByWtype(wtype) {
        var DEFAULT_ROOT_PREFIX = "templates";
        var DEFAULT_TPL = "tpl.html";
        return DEFAULT_ROOT_PREFIX + "/" + wtype + "/" + DEFAULT_TPL;
    };
}]);
1 <div ng-repeat="widget in widgets">
2     <ui-widget ng-model="widget"></ui-widget>
3 </div>

 

posted on 2015-01-26 18:24  zhangwenhao2  阅读(96)  评论(0)    收藏  举报

导航