我正在使用 select2 处理创建一个元素。我为 select2 下拉菜单创建了一个角度指令。但是,如果我在指令呈现后更改 ng-model,则视图不会得到更新。
以下是 Jsfiddle 中一个简单示例的链接:http: //jsfiddle.net/odiseo/zrchy7w0/5/
<div ng-app="miniapp" ng-controller="Ctrl">
<select ng-model="selectedOption" wb-select2 ng-options="k as v for (k, v) in optionList" select-width="300px"></select>
<button ng-click="changeModelOutside()">Click me</button>
var $scope;
var app = angular.module('miniapp', []);
app.directive('wbSelect2', function () {
return {
restrict: 'A',
scope: {
'selectWidth': '@',
'ngModel': '='
},
link: function (scope, element, attrs) {
//Setting default values for attribute params
scope.selectWidth = scope.selectWidth || 200;
element.select2({
width: scope.selectWidth,
});
}
};
});
function Ctrl($scope) {
$scope.optionList = {
'key1': 'Option 1',
'key2': 'Option 2',
'key3': 'Option 3',
'key4': 'Option 4'
};
$scope.selectedOption = 'key3';
$scope.changeModelOutside = function () {
$scope.selectedOption = 'key4';
};
}
顺便说一句,修复应该只在指令的链接函数内进行更改,指令之外的任何修复(我尝试使用 $('option').select2().select2('val','1'))都会只是一种解决方法。
有没有人发现同样的问题并有解决方案?