How to use bindToController, controller, controllerAs and require options instead of a simple link function with an isolated area in this directive?

Scenario:

Suppose I want to create a component that is basically a form that needs to receive some data from the user, validate it, and store it on the server. And I need to expose some callbacks so that the directive user can do what he needs based on the response of the server or user by pressing the cancel button. I want this to be the directive of the <new-product-widget></new-product-widget> element <new-product-widget></new-product-widget> . Now how can I do this? From my point of view, I can simply isolate the scope of the directive and accept functions from the built-in controller as attributes; Example:

 <new-product-widget on-success="ctrl.onAddSuccess" on-error="ctrl.onAddError" on-cancel="ctrl.onAddCancel" on-invalid="ctrl.onAddInvalid"></new-product-widget> 

and then use them inside my link function. However, after going through the docs, I think there is a better way to do this using the bindToController , controller , controllerAs and require options. However, I am confused about how I can rewrite this using these features and the exact benefits that it will provide. Any blog / video links explaining them with an example would be a big help.

Please read the initial description, which may help you understand my confusion.

Original description.

I want to write separate general directives (components). The angular documentation assumes these parameters are related.

My understanding:

  • controller allows me to define a controller constructor. (What special powers give me. What should I do / not do in here)
  • controllerAs allows an alias for the controller within the scope of the directive. (Why do I need access to the constructor? I have to create it manually)
  • require angular doc says - requires a different directive and enters its controller as the fourth argument to the bind function. (eh ..? Why? How?)
  • bindToController angular doc says - if the component uses the selection area (see above) and the controller is bindToController: true , bindToController: true will allow the component to have its properties associated with the controller, and not with the scope. When the instance controller, the initial values ​​of the selection region bindings are already available. (I don’t understand this at all).

Can you explain how to use these parameters together and what they allow me to achieve, which I can not with the communication function? I am very confused.

I am using angular version 1.4.x

[Angular Doc read.] [1]

[1]: https://code.angularjs.org/1.4.7/docs/api/ng/service/ $ compile

+5
source share

Source: https://habr.com/ru/post/1235127/


All Articles