4

I have what seems like a common problem but I can't find anything online on how to achieve what I am trying to do.

I have a search form that contains multiple instances of a common controller that I use to to perform typeahead/autocomplete searches when you type. Each controller is configured with a different parameter to lookup using different criteria. The results of the lookups need to be assigned to a parent property to perform the search based on the entered criteria. So for example:

SearchController

CleanerId
TeacherId
StudentId

And the child controller simply has the notion of a lookup control with an Id and a Text value, where the Id needs to be assigned to the appropriate parent property.

Ideally I want to bind the hidden id field of each controller to both id of the child model and a different property on the parent like below but I don't think that's possible:

< input type="hidden" ng-model="child.Id, parent.CleanerId" />

< input type="hidden" ng-model="child.Id, parent.TeacherId" />

< input type="hidden" ng-model="child.Id, parent.StudentId" />

The child controller has to be generic so how do I make the parent controller bind to the child ids?

Any help is greatly appreciated.

2 Answers 2

2

This is a perfect opportunity to use a directive rather than a controller for the three widgets.

When using the directive, pass the field as an argument:

<child-widget value="parent.CleanerId"></child-widget>
<child-widget value="parent.TeacherId"></child-widget>
<child-widget value="parent.StudentId"></child-widget>

And when defining the directive, pass the value in isolate scope:

app.directive("childWidget", function () {
  return {
    restrict: "E",
    scope: {
      value: "="
    },
    template: '<input type="hidden" ng-model="value" />'
  };
});
Sign up to request clarification or add additional context in comments.

3 Comments

In this instance are you not passing information from the parent to child directive to initialise it? It seems directives might make more sense but how do I pass the hidden id to the parent once it has been set? Does this work in your example/
value is connected using a two-way binding, which means when the parent changes its value, it changes in the directive, and vice versa. So yes, it does work here automatically, no coding needed.
Great will give it a try now
0

This is a perfect blog to get the answers around Parent-Child Controller Communication :

https://rclayton.silvrback.com/parent-child-controller-communication

1 Comment

I had read that article but it doesn't really answer my question. I can create a single child that sets a hard coded parent property but the parent property being set will be different for each instance of the child. That's what I am struggling with.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.