Angularjs ui-select在指令中使用

viz*_*zog 4 angularjs angular-ui ui-select

我在我的cusom指令里面使用angular-ui ui-select指令叫做timezone.问题是当从列表中选择时区时,不会更新周围控制器的模型对象.这是我的指令代码:

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"];
    }
};
});
Run Code Online (Sandbox Code Playgroud)

我的控制器:

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

这是我在html中使用它的方式:

<div ng-app="MyApp" ng-controller="MyCtrl">
  {{foo}}<br />
  <timezone tz-model="foo.name" />
</div>
Run Code Online (Sandbox Code Playgroud)

问题是,当我从下拉列表中选择一个新值时,我的控制器对象不会更新. 这是jsFiddle 我猜ui-select有问题,因为我和其他组件做了同样的工作.

小智 5

您需要在ui-select指令中设置ng-model ="tzModel.name".

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" ...
Run Code Online (Sandbox Code Playgroud)

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