Siri
Siri

Reputation: 33

Reuse function Angular 1

Let's say I have 2 lists of items: available items and associated items. now I want to write a search function that calls API methods that do the search for each list (different methods). I want to sign the search results into models using $scope object. Like this:

 $scope.availableItems.data = response.data;

What is the best way to write a reusable search method in this case?

Upvotes: 2

Views: 42

Answers (1)

Tim Consolazio
Tim Consolazio

Reputation: 4888

Put your search methods into a service, inject the service into your components. Bind to the values in the service, or better, create a getter in your components and return the value from the injected service.

Something like:

In your service:

this.searchVal = '';

executeSearch ( searchTerm ) {
   // The usual http angular stuff etc.
   .then ( function ( d ) {
      this.searchVal = d; // however you do it in your code
   }
}

In your components, into which you inject your searchService:

function getSearchValue ( ) {
   return myInjectedService.searchVal;
}

In your component templates, bind to the getter, say you put the getSearchValue on the scope:

{{getSearchValue()}}

Upvotes: 1

Related Questions