4

I have a project where we are using a lot of angular ui-select directives. The usage of the ui-select is standardized and the only difference between the various points we use it is the ui-select-choice template and the service used to fetch the results. I'm trying to write a Picker directive that wraps the ui-select. The problem I'm encountering is transcluding the ui-select-choice template.

Here is the directive I've written.

registerDirective("picker", ["$injector", ($injector): IDirective => {
    return {
        restrict: "E",
        templateUrl: "/Scripts/App/Views/Picker.html",
        transclude: true,
        scope: { model: "=model", sourceName: "=sourceName" },
        link: ($scope: interfaces.IPickerScope, $: JQuery, attrs: ng.IAttributes) => {
            var service = <services.IPickerService>$injector.get($scope.sourceName + "Service");

            $scope.fetchResults = (filter: string) => {
                service.pickerSearch(filter).then((response: any[]) => {
                    $scope.results = response;
                });
            };
        }
    };
}]);

The Directive View:

<ui-select ng-model="$parent.model" reset-search-input="false">
<ui-select-match placeholder="Enter Item Name"><span ng-bind-html="$select.selected.name"></span></ui-select-match>
<ui-select-choices repeat="item in results"
                   refresh="fetchResults($select.search)"
                   refresh-delay="1000">
    <div ng-transclude>

    </div>
</ui-select-choices>

And here is an example usage of the directive:

<picker source-name="'plu'" model="selectedItem">
  <span ng-bind-html="item.formattedName | highlight: $select.search"></span>
  <small ng-show="item.used"><em>(already in use)</em></small>
</picker>

I'm still learning the in's and out's of angular and this is my first experiment with transcluding. I've noticed that the picker is using the transcluded template, but none of the scope variables are being set. I'm pretty sure this is a scope problem related to the way transclude and scope behave. I've looked into using the compile and transclude function but can't seem to quite get to where I need to be with that.

DanielC
  • 271
  • 4
  • 8

1 Answers1

0

Remove the specification of scope for the directive. If you do specify it, the directive will create a scope of it's own and the transcluded part will be bound to the outter scope. If you don't specify a scope for the directive, both the directive and the transcluded part will be bound to the outter scope, allowing the behaviour that you're looking for.

Fernando Pinheiro
  • 1,796
  • 2
  • 17
  • 21