0

I have a directive that look like this:

<div ng-controller="searchController" searchbar>
   <input type="text" id="searchfield" ng-model="myVar">
   <div searchresult>
       <div ng-repeat="data in data.menu | filter: myVar">
           {{data.title}}
       </div>
   </div>
</div>

There is one controller called searchController, and 2 directives called searchbar and searchresult.

How can I have the searchbar directive to run a function in searchresult directive? I was thinking to put require: "^searchresult" in searchbar directive and call it's function. Is that the correct way of doing? What if the searchresult is not available there?

Here is the detail scenario:

When user type in the input field, the search result update by the filter. Therefore the height of searchresult div is changed.

How can the searchresult directive knows about the changes of the height & run the required function instantly?

1 Answer 1

1

searchResult can have reference to searchBar not the other way around. As from documentation

^ - Locate the required controller by searching the element and its parents. Throw an error if not found.

Also look at ^? for optional dependencies. See compile documentation.

If you detail your scenario, we can help better.

Update: Based on the scenario that you have outlined, you can directly watch myVar property in searchresult directive and whenever it changes you can trigger the function to resize the results.

Assuming that the searchresult directive does not create isolated scope. You can try, such a code inside your directive link function

scope.$watch('myVar',function(newValue) {
   $timeout(function() {
       //do some work here
   },0);
});

Timeout helps as we cannot be sure when the rendering of the list is complete.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for your answer. I have updated the question with detail scenario and I have stuck here for few days already. Hope you can give a help here. Thanks.
Thanks for the updated answer. But how can I watch myVar? How can I ensure that the function is triggered only after the result is being filtered & updated to new height? It would be great if you could show an example of code for better understanding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.