为什么有的要写在link里面,有的要写在controller里面?!
如果希望在module中设置一个子scope,但不用directive,这时候能否用link?
(比如说用ngRoute时候的ng-view部分,可否用link)
controller可以和服务器端通信是吧,link好像不干这事情?还是只是我没见到过?
高洛峰2017-05-15 16:53:39
About the difference between link and controller in directive?
1. Execution order: controller first and then link
2. When to use controller: In general scenarios, you don’t want to use controller, you just need to write the logic in the link; the scenario where controller is used is that the instruction (assumed to be a) will be required by other instructions (assumed to be b) When, this controller will be passed in the link function of the b instruction (if there are multiple require, an array will be passed in, and the controller corresponding to each require instruction will be stored in the array). The purpose is obviously For communication between instructions.
Can I use link for non-directive scopes?
The link is called only in the instruction, which means that the link is called when the instruction is bound to the scope after compile.
Link is only used in the place where the instruction is defined. It can also be used in other places. For example, when making a pop-up box, you need to get the template tpl and then call var linkFn = $compile(angular.element(tpl));
此时返回的就是一个link的函数,然后linkFn(scope)
. The scope here is the scope you need to specify. It can be a new one. Created or already existing.
某草草2017-05-15 16:53:39
link and controller are completely unrelated concepts.
For a specific directive, there may be no controller. The link is more complicated and can basically be regarded as a callback of $compile. For angularjs, the directive must be compiled first ---> Call $compile to generate the dom object ---> ; Call link to bind to the corresponding scope ---> Trigger $digest (there are many steps after that to update a directive. The compilation times and timing of different objects are different, see the API for details)
In short, compile, link and the like are all for directional. If the subject is familiar with jquery, then the compile process is equivalent to creating some dom objects ($('<a class = //.... ') ) link is a DOM operation such as $().append or prepend.
So what is scope? Scope is used to bind models.
What is a controller? Used to add methods (logic) to the scope.
link is an aspect mechanism provided by AngularJS for embedding directives into DOM. Controller is the context when the watch event in the scope is triggered, which is completely different.
As for the last question, as long as the function can be run, the code you write can be executed, but generally speaking
1) Write your business logic in the controller, and don’t write it in the directive’s own controller, but in the controller of the scope it is bound to
2) Do not have DOM operations in the controller, especially prepend and append, because uncompiled DOM objects cannot be watched, and angularjs will not monitor DOM objects that are added later and have not been compiled.