typescript - Call AngularJS 1.5 component's method from the controller? -
i have component plugged main page this
<rs-dropdown></rs-dropdown>
the component defined rsdropdowncomponent class reference rsdropdowncontroller, usual stuff...
the component has $oninit() event handler calls datastore populate component data, event fired once component initialized.
the problem dont want component start loading data oninit() event.
i want able call component's method controller when want to.
basically need somehow access instance of component controller , call it's load function.
is possible?
someone mentioned using ng-if, or making child component more lenient asynchronous inputs better approach if possible, there's many things can do.
1 - can use eventing, create simple event service signatures like:
service.registereventhandler(id, function) service.unregistereventhandler(id, function) service.sendevent(id)
register handler in child, , fire event parent when ready
2 - dark magic using 2-way bindings. in child component specify
bindings: { darkmagic: '=' }, controller: function() { this.$oninit = function() { darkmagic = function() { // data ready }; ...
then parent template <child data-dark-magic="$ctrl.placeholder">....
in parent controller, after compile, after postlink after digest cycle... can call this.placeholder();
execute function defined in child.
3 - can use one-way binding onchanges toggle state
controller: function() { this.ready = false; // should use oninit saving lines this.$onchanges = function(changesobj) { if (changesobj.isreadyproperty) { this.ready = changesobj.isreadyproperty.currentvalue; } } }, bindings: { isreadyproperty: '<', }
then parent have <child is-ready-property="$ctrl.imready">...
, toggle imready true in controller when data loaded.
there case when child under parent, example of tabset component , tab components. in case child (tab) component can require tabset controller, , use api defined there.
or use service communication, inject service both components, , maintain state way. keep in mind solutions though use factory patterns , not maintain state in angular recipes.
i'm sure there's many more ways, depends on use-case.
i still prefer make component more lenient handle no data case gracefully until receives something.
cheers
Comments
Post a Comment