问题
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:
From within
compile
specifying bothpreLink
andpostLink
functions explicitly:compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { ... }, post: function postLink(scope, iElement, iAttrs, controller) { ... } } }
From within
compile
returning onlypostLink
implicitly:compile: function compile(tElement, tAttrs, transclude) { return function postLink( ... ) { ... } }
From within
link
specifying bothpreLink
andpostLink
explicitly:link: { pre: function preLink(scope, iElement, iAttrs, controller) { ... }, post: function postLink(scope, iElement, iAttrs, controller) { ... } }
From withing
link
usingpostLink
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