Search code examples
javac#asp.netangularjsangularjs-scope

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?


Solution

  • 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()}}