简体   繁体   中英

AngularJS passing a model down to ui-select

I have the following scenario:

  1. A form has a directive called <timeZone ng-model="formModel.timeZone"
  2. This directive calls a web service to retrieves a timezone
  3. The directive then puts them in a ui-select

The form does not care about the list of timezones, this is all contained within the directive. It only cares about getting and setting the selected timezone.

Code - Form:

<time-zone name="preferredTz" ng-model="profileDetails.preferredTz" ng-required="true"></time-zone>

Code - Directive (JS):

.directive('timeZone', function (staticCommonResourcesAPI) {
        return {
            restrict: 'E',
            require: 'ngModel',
            templateUrl: 'shared/partials/timezoneField.tpl.html',
            link: function(scope, element, attr, ngModel){
                scope.timezones = [];
                staticCommonResourcesAPI.getTimezones().then(function (response) {
                    scope.timezones = response.payload;
                });
            }
        };
    });

Code - Directive (HTML Template)

<ui-select
        id="timezoneCode"
        name="timezoneCode"
        required="true"
        theme="bootstrap"
        ng-disabled="disabled || signupStatusTag">
    <ui-select-match>{{$select.selected.code}}</ui-select-match>
    <ui-select-choices repeat="timezone.code as timezone in timezones | filter: $select.search" class="ui-select-override-top-style">
        <span class='no-underline'>{{timezone.name}}</span>
    </ui-select-choices>
</ui-select>

If I'm understanding how ui-select works properly, I need to bind profileDetails.preferredTz with the uiSelectModel.selected .

I've tried using scope : true , but so far all that's happening is the ui-select is using a different model altogether, or ends up setting the profileDetails.preferredTz to undefined upon initialization.

Try using nForm

<ng-form timezone ng-model="myModel">

 ...uiSelect

</ng-form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM