angular $compile 编译html,angular之$compile

$compile服务会遍历DOM树并搜索它找到的所有指令,然后将所有这些指令的链接函数合并为一个单一的链接函数。

然后这个链接函数会将编译好的模版链接到$rootScope中。

他会通过检查DOM属性,注释,类以及DOM元素名称的方式查找指令。

ps

angular的事件循环被称为 $digest 循环。

$digest分为两个小型循环 $watch  evalAsync

案例

angular.module('app',[])

.directive('jxBindCompiledHtml',function($compile){

return {

template:'

scope:{

rawHtml:'=jxbBindCompiledHtml'

},

link:function(scope,elem,attrs){

scope.$watch('rawHtml,function(value){

if(!value) return;

// 这边就是利用$compile 来实现 展示html 数据的。

var newElement = $compile($.parseHTML(value))(scope.$parent);

elem.contents().remove();

elem.append(newElement);

})

}

}

})

使用 $compile 可以动态的编译服务器端返回的html片段,比如html片段中还有类似 ng-click 代码的话,必须使用$compile来执行动态编译才能够将ng-click动态编译上去。

案例:

angular.module('compileExample', [], function ($compileProvider) {

// configure new 'compile' directive by passing a directive

// factory function. The factory function injects the '$compile'

$compileProvider.directive('compile', function ($compile) {

// directive factory creates a link function

return function (scope, element, attrs) {

scope.$watch(function (scope) {

// watch the 'compile' expression for changes

return scope.$eval(attrs.compile);

}, function (value) {

// when the 'compile' expression changes

// assign it into the current DOM

element.html(value);

// compile the new DOM and link it to the current

// scope.

// NOTE: we only compile .childNodes so that

// we don't get into infinite loop compiling ourselves

$compile(element.contents())(scope);

});

};

});

}).controller('GreeterController', ['$scope', function ($scope) {

$scope.name = 'Angular';

$scope.html = 'Hello ';

}]);

PS:还有需要注意的就是,对于使用了$compile之后,有的是需要执行$scope.$digest() 方法执行下脏检查的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值