zoukankan      html  css  js  c++  java
  • 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的数据显示出来了。

  • 相关阅读:
    CF140C New Year Snowmen
    CF1131G Most Dangerous Shark
    莫比乌斯函数&欧拉函数&筛法 综合运用
    【51nod1220】约数之和
    题解[CF1228E Another Filling the Grid]
    dsu on tree学习笔记
    线性基学习笔记
    题解[CF895C Square Subsets]
    博弈论学习笔记
    题解[ [JSOI2007]文本生成器 ]
  • 原文地址:https://www.cnblogs.com/darrenji/p/4975383.html
Copyright © 2011-2022 走看看