我正在努力创建一个使用Select2处理的元素。我为Select2下拉菜单创建了一个Angular指令。但是,如果我在指令渲染后更改NG模型,则该视图将无法更新。
以下是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';
};
}
顺便说一句,修复程序应仅进行更改 ince 指令的链接函数,任何修复外部>使用$('option')。select2()。select2('val','1')将只是一个工作。
有人找到了同样的问题并为此提供解决方案?
您可以查看此JSFIDDLE。
http://jsfiddle.net/zrchy7w0/6/
<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="350px" style="width:300px"></select>
<button ng-click="changeModelOutside()">Click me</button>
</div>
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,
});
scope.$watch('ngModel', function(newValue, oldValue){
element.select2().val(newValue);
});
}
};
});
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';
};
}