AngularJS如何編譯和呈現頁面


 

AngularJS如何編譯和呈現頁面?

頁面加載,首先加載靜態DOM,AngularJS隨即加載,並尋找在頁面的ng-app,然后開始編譯所有moudlue內的所有service, controller,directive等,然后搜尋dom中的directive,並創建HTML模板,模板就有了自己的scope,scope中的數據顯示到view上,最終呈現頁面。而談到編譯,使用了AngularJS的一個service,叫做$compile。

 

var app = angular.module('myApp',[]);

app.directive('contentItem', function($compile){
    var imageTemplate = '...href="{{rootDirectory}}{{content.data}}"...';
    var videoTemplate = '..ng-src="{{content.data}}"...';
    var noteTemplate = '...{{content.title}}...';
    
    var getTemplate = function(contentType){
        var template = '';
        
        switch(contentType){
            case 'image':
                template = imageTemplate;
                break;
            case 'video':
                template = videoTemplate;
                break;
            case 'notes':
                template = noteTemplate;
                break;
        }
        
        return template;
    }
    
    
    var linker = function($scope, element, attrs){
        $scope.rootDirectory = 'images/';
        element.html(getTemplate($scope.content.content_type)).show();
        $complie(element.contents())($scope);
    }
    
    return {
        restrict: "E",
        replace: true, //表示這里創建動態創建的html模板會覆蓋頁面中原先靜態的html
        link: linker,
        scope: {
            content: '='
        }
    };
});

 

以上,最關鍵的是$complie(element.contents())($scope);當我們在頁面中使用<content-item></content-item>的時候,AngularJS的$complie服務動態編譯創建HTML模板,並把當前的$scope賦值給該HTML模板,這樣就把$scope的數據顯示出來了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM