Can AngularJS directive pre-link and post-link functions be customized?

拈花ヽ惹草 提交于 2019-12-31 10:42:26

问题


I have seen many references to AngularJS pre- and post-link functions in literature about AngularJS.

I am not sure however whether these can be customized or are internal to the framework.

In other words, as an AngularJS developper, can I provide my own pre and post link functions to my custom directives?


回答1:


Yes you can, as per @Mikke's answer. To sum up, there are four ways to declare linking functions:

  1. From within compile specifying both preLink and postLink functions explicitly:

    compile: function compile(tElement, tAttrs, transclude) {
      return {
        pre: function preLink(scope, iElement, iAttrs, controller) { ... },
        post: function postLink(scope, iElement, iAttrs, controller) { ... }
      }
    }
    
  2. From within compile returning only postLink implicitly:

    compile: function compile(tElement, tAttrs, transclude) {
      return function postLink( ... ) { ... }
    }
    
  3. From within link specifying both preLink and postLink explicitly:

    link: {
      pre: function preLink(scope, iElement, iAttrs, controller) { ... },
      post: function postLink(scope, iElement, iAttrs, controller) { ... }
    }
    
  4. From withing link using postLink implicitly:

    link: function postLink( ... ) { ... }
    



回答2:


Yes, you can provide your own pre and post link functions. See the directive blueprint at Angular Docs' Comprehensive Directive API.

{
    compile: function compile(tElement, tAttrs, transclude) {
        return {
            pre: function preLink(scope, iElement, iAttrs, controller) { ... },
            post: function postLink(scope, iElement, iAttrs, controller) { ... }
        }
        // or
        // return function postLink( ... ) { ... }
    },
}


来源:https://stackoverflow.com/questions/22105336/can-angularjs-directive-pre-link-and-post-link-functions-be-customized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!