我的问题基于此处提出的类似问题: Two way databinding in Select2 for AngularJS doesn't work
这个问题已得到回答,并提供了一个可用的 plunker:http://plnkr.co/edit/MKy2IU?p=preview
主要代码是一个选择框:
<select ui-select2="{width: 'element'}" style="width: 200px" placeholder="All" ng-model="chosenItem">
<option value=""></option>
<option ng-repeat="item in filterItems" value="{{item.id}}">{{item.text}}</option>
</select>
和更新选择控件的函数。这在 plunker 中很有效。
我 fork 了 plunker,只将 Angular 版本从:1.0.7 更改为:1.2.13(我正在使用)
这是 fork 的 plunker http://plnkr.co/edit/bcowo3bHKC2XvWDrv6V2?p=preview使用 angular 1.2.13,您可以在 plunker 中看到模型已更新,但 View 不受影响,此外,当您打开选择框时,您会看到值已被选中但未被选中。
知道如何让它发挥作用吗?
最佳答案
我没有使用过 select2 插件,但似乎随着你的 Angular 更新,你的 select2 指令的优先级需要高于 ng-model
的优先级,即 0
,所以我只是为指令提供了一个优先级 1
,它现在可以工作了。
在 ui-select2 中更改:-
angular.module('ui.directives').directive('uiSelect2', ['ui.config', '$timeout', function (uiConfig, $timeout) {
var options = {};
if (uiConfig.select2) {
angular.extend(options, uiConfig.select2);
}
return {
require: '?ngModel',
priority: 1, //<--- Here
如果您真的不想接触插件源代码(我建议以后进行任何升级),请在您的应用程序中将优先级设置为配置,并在获得此指令的工作版本后将其删除。还要验证他们是否有已修复的更新版本。
//Remove later once plugin is fixed
app.config(function($provide){
return $provide.decorator('uiSelect2Directive', ['$delegate', function($delegate) {
$delegate[0].priority = 1; //Just set the priority
return $delegate;
}])});
关于javascript - AngularJS 的 Select2 中的两种方式数据绑定(bind)在 Angular 1.2.13 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25694021/