Wrapping Angular.js ui-bootstrap or ui-select directives in native directive

I am building a large Angular.JS app that uses some third party modules like ui-select and ui-bootstrap. To avoid repetition, I started to create directives that wrap like ui-select code and logic to fetch / find data.

Goal : The goal was to create a directive that can be used in a template like this without duplicating code in controllers:

<tq-car-select ng-model="model.car"></tq-car-select>

      

I try to avoid:

<select ng-options="car.id as car.name for car in cars"></select>

      

and duplicate the following code in all controllers that use selection:

$scope.cars = carResource.query();
$scope.$watch('model'), function (newValue, oldValue) {
    $scope.cars = carResource.query({model: $scope.model});
});

      

I have created directives for such select fields.

Actual example with ui-select :

Tq-lead-select.html:

<ui-select ng-model="$parent.tqModel" style="display: block">
    <ui-select-match placeholder="tippen ...">{{$select.selected.bezeichnung}}</ui-select-match>
    <ui-select-choices repeat="lead in leads | filter:{bezeichnung: $select.search}">
        <div ng-bind-html="lead.bezeichnung | highlight: $select.search"></div>
    </ui-select-choices>
</ui-select>

      

tqLeadSelect.ts (TypeScript):

export function tqLeadSelect(tqLeadSelects): ng.IDirective {

var dir: ng.IDirective = {};

dir.scope = {
    tqModel: '=',
    tqCompany: '='
};

dir.restrict = 'E';
dir.templateUrl = '/js/templates/leadApp/tq-lead-select.html';
dir.replace = false;

dir.controller = function ($scope: any) {
    if (tqLeadSelects != null && $scope.tqCompany != null) {
        $scope.leads = tqLeadSelects.getLeadsFromFirma({ id: $scope.tqCompany });
    }

    $scope.$watch('tqCompany', (newValue, oldValue) => {
        if (newValue === oldValue) return;

        $scope.leads = tqLeadSelects.getLeadsFromFirma({ id: $scope.tqCompany });
    }, true);
}

return dir;
}

tqLeadSelect.$inject = ['tqLeadSelects'];

      

Problems

  • I need an isolated area because some views use multiple instances of the same field.
  • I am using the scope tqModel isolated variable which is set by the ngModel of the ui-select directive
  • I would like to use ng-required without creating the tq scope variable required by the tqLeadSelect directive

Questions

  • Am I doing it right? Are there any better ways to achieve my goals?
  • how do you define select fields with supporting controller code for data retrieval and additional functionality?
+3


source to share


1 answer


One solution would be to add a directive that extends the existing directive.

I created Plunker with an example: http://plnkr.co/edit/9IZ0aW?p=preview

The following code:

HTML:

<ui-select ng-model="address.selected" theme="bootstrap" ng-disabled="disabled" reset-search-input="false" style="width: 300px;">
  <ui-select-match placeholder="Enter an address...">{{$select.selected.formatted_address}}</ui-select-match>
  <ui-select-choices repeat="address in addresses track by $index" refresh="refreshAddresses($select.search)" refresh-delay="0">
    <div ng-bind-html="address.formatted_address | highlight: $select.search"></div>
  </ui-select-choices>
</ui-select>

      

Controller:

$scope.address = {};
$scope.refreshAddresses = function(address) {
  var params = {
    address: address,
    sensor: false
  };
  return $http.get(
    'http://maps.googleapis.com/maps/api/geocode/json', {
      params: params
    }
  ).then(function(response) {
    $scope.addresses = response.data.results
  });
};

      



can be simplified using the config directive:

<ui-select ng-model="adress.selected" tq-select></ui-select>

      

The controller is now empty!

Directive

app.directive("tqSelect", function($http) {

  return {
    restrict: "A", // Attribute
    require: ["uiSelect", "ngModel"],

    compile: function compile(tElement, tAttrs, transclude) {

      // Add the inner content to the element
      tElement.append('<ui-select-match placeholder="Enter an address...">{{$select.selected.formatted_address}}</ui-select-match>\
      <ui-select-choices repeat="address in addresses track by $index" refresh="refreshAddresses($select.search)" refresh-delay="0">\
        <div ng-bind-html="address.formatted_address | highlight: $select.search"></div>\
      </ui-select-choices>');

      return {
        pre: function preLink(scope, iElement, iAttrs, controller) {},
        post: function postLink(scope, iElement, iAttrs, controller) {

          // logic from controller
          scope.address = {};
          scope.refreshAddresses = function(address) {
            var params = {
              address: address,
              sensor: false
            };
            return $http.get(
              'http://maps.googleapis.com/maps/api/geocode/json', {
                params: params
              }
            ).then(function(response) {
              scope.addresses = response.data.results
            });
          };
        }
      }
    }
  }
});

      

The directive is the really tricky part. I am using non-trivial logic in the compilation function. First, I add the required markup for the ui-select directive.

Then, in the post-link function, I added the logic that is usually found in the controller (or in the link () function).

+4


source







All Articles