0

How can I reuse code if i have more than one ui-select in my angular app and all dealing with different remote API to show options?

With reference to AngularJS Wrapping a ui-select in a custom directive, I've got an idea that wrapping ui-select in custom diretive will help to reuese code but again I will have to write different code for controller to call different API endpoints.

2 Answers 2

0

1) You don't have to code different controllers. If all the differents API return the same objects structures you just have to add a binding attribute to your custom directive giving the API url. Then, the controller of your custom directive will be able to use it.

2) Otherwise, you will have to create an object or interface for the returning data and a single controller that can deal with the different APIs.

3) Or, you can also create your custom directive with a binding attribute that is a factory to your objects. Then, you will have to give the factory method to your directive when you want to use it.

If you don't know about binding attributes, check this.

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

Comments

0

I've followed the answer of @Floc and managed to make a custom reusable directive.If someone is stuck with same problem then they can refer this code.

Directive

  app.directive('tagInput',function($http){
  return{
  restrict : 'E',
  templateUrl : 'tag-input.html',
  scope:{
    placeholder : '@',
    ngModel : '='    
  },
  link:function(scope,elem,attrs){
  scope.addresses = [];
  scope.refreshAddresses = function(address){
    var params = {address:address,sensor:false};
    return $http.get(attrs.url,{params:params})
      .then(function(response){
        scope.addresses = response.data.results[0].address_components;
      })
     }
   }
  }
  })

template

<ui-select style="width:50%"  ng-model="$parent.ngModel" theme="select2">
<ui-select-match placeholder="{{placeholder}}">{{$select.selected.long_name}}</ui-select-match>
<ui-select-choices repeat="address in addresses track by $index" refresh="refreshAddresses($select.search)" refresh-delay="0" >
     <span ng-bind-html="address.long_name| highlight: $select.search"></span>
</ui-select-choices>

And pass required parameters here(in my case it is url and placeholder)

<tag-input url="https://maps.googleapis.com/maps/api/geocode/json" placeholder="hello"></tag-input>

Comments

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.