400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

angular指令中preLink和postLink函数的示例分析

这篇文章将为大家详细讲解有关angular指令中preLink和postLink函数的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

创新互联-专业网站定制、快速模板网站建设、高性价比凤泉网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式凤泉网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖凤泉地区。费用合理售后完善,10余年实体公司更值得信赖。

指令模板选项有complie和link两个字段,两者之间存在如下关系:

而link分为preLink和postLink两个阶段,从link字段或者compile函数的返回值来看:

app.directive('myDirective', function () {
  return {
      compile: function () {
          return {
              pre: function () {
                  console.log('preLink');
              },
              post: function () {
                  console.log('postLink');
              }
          }
      }
  }
});

我们的指令工厂返回的是一个函数,那么angular通过这样的包装  directive = { compile: valueFn(directive) },即该函数将作为指令对象的postLink函数,像这样:

app.directive('myDirective', function () {
  return function () {
    console.log('postLink');
  }
});
angular编译链接指令的顺序

为了看清angular编译链接指令的顺序,用以下代码输出日志的方式来说明:


    
        
        
            
            
              
            
        
        
    

 
var app = angular.module('myApp', []);
var names = ['a1', 'b1', 'b2', 'e1', 'd1'];
 
names.forEach(function (name) {
  app.directive(name, function () {
    return {
        compile: function () {
             console.log(name + ' compile');
            return {
                pre: function () {
                    console.log(name + ' preLink');
                },
                post: function () {
                    console.log(name + ' postLink');
                }
            };
        }
    };
  });
});

输出:

a1 compile
b1 compile
b2 compile
e1 compile
d1 compile
a1 preLink
b1 preLink
b2 preLink
b2 postLink
b1 postLink
e1 preLink
e1 postLink
d1 preLink
d1 postLink
a1 postLink

可以看出:

明白了这些以后,就要小心一些容易忽略的陷阱。


    

 
var app = angular.module('myApp', []);
 
app.directive('myParent', function () {
    return {
        restrict: 'EA',
        template: '
{{greeting}}{{name}}'+         ''+         '
',         link: function(scope,elem,attr){             scope.name = 'Lovesueee';             scope.greeting = 'Hey, I am ';         }     }; }); app.directive('myChild', function () {     return {         restrict: 'EA',         template: '
{{says}}
',         link: function(scope,elem,attr){             scope.says = 'Hey, I am child, and my parent is ' + scope.name;         }     }; });

结果子指令输出为undefined

Hey, I am Lovesueee
Hey, I am child, and my parent is undefined

由上可以,myParent指令的link是一个postLink函数,而这个函数将在myChild指令的preLink和postLink执行完之后才执行。所以scope.name = undefined。

关于“angular指令中preLink和postLink函数的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。


文章名称:angular指令中preLink和postLink函数的示例分析
URL分享:http://www.bluegullmedia.com/article/pdpgse.html

其他资讯

让你的专属顾问为你服务

0.0395s