我在我的自定义指令中使用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"];
}
};
});
我的控制器:
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>
问题是,当我从下拉列表中选择一个新值时,我的控制器对象没有更新。这是jsFiddle我猜ui-select有问题,因为我已经用其他组件做了同样的工作。
你需要在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/我修改了你的小提琴,看看这个,它工作了->小提琴
您必须做以下更改
在view.html<div ng-app="MyApp" ng-controller="MyCtrl">
{{foo.name}}<br />
<timezone tz-model="foo" />
</div>
将第三行改为z-model = "foo"
在controller.jsvar 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" ....希望能有所帮助