Angularjs ui-select used in directive

I use the angular -ui ui-select directive inside my cusom directive called the time zone. The problem is that the model object of the surrounding controller is not updated when the time zone is selected from the list. Here is my directive code:

var myApp = angular.module('MyApp', ['ui.select','ngSanitize']);

myApp.directive('timezone', function () {
return {
    restrict: 'AE',
    template: '<ui-select theme="bootstrap" ng-model="tzModel" style="min-width: 300px;"> <ui-select-match placeholder="Select a timezone in the list">{{$select.selected}}</ui-select-match> <ui-select-choices repeat="tz in timezones | filter: $select.search"> <div ng-bind-html="tz"></div> </ui-select-choices> </ui-select>',

    scope: {
        tzModel : '=',
    },
    link: function(scope) {
        scope.timezones = ["Africa/Abidjan", "UTC"];
    }
};
});

My controller:

myApp.controller('MyCtrl', function ($scope) {
  $scope.foo = {name:"Africa/Abidjan"};
});

This is how I use it in html:

<div ng-app="MyApp" ng-controller="MyCtrl">
  {{foo}}<br />
  <timezone tz-model="foo.name" />
</div>

The problem is that when I select a new value from the drop-down list, my controller object is not updated. Here is jsFiddle. I think there is a problem with ui-select, because I did the same work with other components.

+4
source share
2 answers

You need to set ng-model = "tzModel.name" in the ui-select directive.

https://github.com/angular-ui/ui-select/wiki/FAQs#ng-model-not-working-with-a-simple-variable-on-scope

<timezone tz-model="foo" />

<ui-select theme="bootstrap" ng-model="tzModel.name" ...

https://jsfiddle.net/XyUGE/264/

+5

, , → fiddle

view.html

<div ng-app="MyApp" ng-controller="MyCtrl">
    {{foo.name}}<br />
    <timezone tz-model="foo" />
</div>

tz-model = "foo"

.js

var myApp = angular.module('MyApp', ['ui.select','ngSanitize']);

myApp.controller('MyCtrl', function ($scope) {
    $scope.foo = {name:"Africa/Abidjan"};
});

myApp.directive('timezone', function () {
    return {
        restrict: 'AE',
        template: '<ui-select theme="bootstrap" ng-model="tzModel.name" style="min-width: 300px;"> <ui-select-match placeholder="Select a timezone in the list">{{$select.selected}}</ui-select-match> <ui-select-choices repeat="tz in timezones | filter: $select.search"> <div ng-bind-html="tz"></div> </ui-select-choices> </ui-select>',

        scope: {
            tzModel : '=',
        },
        link: function(scope) {
            scope.timezones = ["Africa/Abidjan", "UTC"];
        }
    };
});

"tzModel.name" "tzModel".... ,

+3

All Articles