Angularjs $compile使用示例

代码如下:

var infographicModule = angular.module('infographicModule',[]); 
infographicModule.directive('bodyTextInfographic', ['$compile','$timeout','jsonService',function($compile,$timeout,jsonService) {

    return{
        restrict: 'C',
        
        link: function (scope, iElement, iAttrs) {
            var tempURL=scope.source['default'].href || scope.source['medium'].href || scope.source['small'].href;
            
            if(tempURL){
                
                var resultingElement = "<div class='infographic_iframe_container'>"+
                                            "<iframe onLoad='infoloadfun()' class='infographic_iframe' frameborder='0' scrolling='auto' src="+ tempURL +"></iframe>"+
                                        "</div>";
                
                
                var linkFn = $compile(resultingElement);
                var newElement = linkFn(scope);
                iElement.replaceWith(newElement); //这里的iElement也可以替换成页面上的任意元素
            }
        }
    }

}]);

//另一使用示例:(
iElement也可以替换成页面上的任意元素
var jqEle = floatMenuContentEl.find("."+viewName+"Pane");
var tplPath = HTML_RENDITION.documentsPath_version +'views/'+viewName+'Pane.html?ts=' + scope.timestamp;
var tpl = $compile("<div style='width:280px;' ng-include=\"'"+tplPath+"'\"></div>")(jqEle.scope());
jqEle.html(tpl);

相比传统的template,$compile更为灵活

 

posted @ 2018-11-06 10:19  jim520  阅读(1195)  评论(0)    收藏  举报