我正在使用select2处理创建元素。我为select2下拉列表创建了一个angular指令。但是,如果我在渲染指令后更改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'))将只是一个解决方法。
有没有人发现同样的问题,并为此有解决方案?
答案 0 :(得分: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';
};
}