angular之$compile

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

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

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



ps

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

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

案例

angular.module('app',[])
.directive('jxBindCompiledHtml',function($compile){
    return {
        template:'<div></div>',
        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动态编译上去。


案例:

<div ng-controller="GreeterController">
    <input ng-model="name">
    <textarea ng-model="html"></textarea> 
    <div compile="html">
    </div>
</div>

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() 方法执行下脏检查的。




你可能感兴趣的:(Angular)