The scenario:
Say I want to create a drop in component which is basically a form that needs to take some input from the user, validate it and save it on the server. And I need to expose some callbacks so that the user of the directive can do what he needs based on the server response or user clicking the cancel button. I want this to be an element directive <new-product-widget></new-product-widget>
. Now how do I go about doing this? From my point of view I can simply isolate the scope of the directive and accept functions from the enclosing controller as attributes; Ex:
<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 directive docs I think there is a better way to do this using the bindToController
, controller
, controllerAs
and require
options. However I am confused as to how I can rewrite this using these features and the precise benefits it will provide. Any links to blogs/videos explaining these by example would be a great help.
Please read the original description it might help you in understanding my confusion.
Original description.
I want to get into writing isolated shareable directives (components). The angular documentation suggests that these options are related.
My understanding:
Controller
allows me to define a controller constructor. (What special powers does this give me. What should I be doing/not doing in here)ControllerAs
allows an alias for the controller inside directive scope. (Why would I need access to the constructor? Am I supposed to instantiate it manually)Require
angular doc says - Require another directive and inject its controller as the fourth argument to the linking function. (eh..? Why? How?)bindToController
angular doc says - When an isolate scope is used for a component (see above), and controllerAs is used,bindToController: true
will allow a component to have its properties bound to the controller, rather than to scope. When the controller is instantiated, the initial values of the isolate scope bindings are already available. (I don't understand this option at all.)Can you explain with an example how to use these options together and what they allow me to achieve which I can't with the link function? I am very confused.
I am using angular version 1.4.x
[Angular Doc I read.][1]
[1]: https://code.angularjs.org/1.4.7/docs/api/ng/service/$compile