Angularjs ui-select在指令中使用

时间:2015-07-09 09:22:36

标签: angularjs angular-ui ui-select

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

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"];
    }
};
});

我的控制器:

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

以下是我在html中的使用方法:

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

问题是当我从下拉列表中选择一个新值时,我的控制器对象不会更新。 Here is the jsFiddle 我猜ui-select存在问题,因为我和其他组件做过相同的工作。

2 个答案:

答案 0 :(得分: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" ...

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

答案 1 :(得分:3)

我改变了你的小提琴,看看这个,它正在发挥作用 - &gt; fiddle

您必须进行以下更改

在view.html中

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

将第3行更改为tz-model =“foo”

在controller.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”....希望它有所帮助