我是棱角分明的新人,在研究了2天之后,我仍然没有想出一个可行的解决方案。
我有一个选项会更新其选项,我也使用bootstrap-select.js。我可以自己动手工作(角度项在标准选择列表中按预期动态更新,或者使用bootstrap-select项来处理静态选项)。如果有人可以提供一些关于我做错的指导,我们将不胜感激!这是我的代码:
HTML:
<div ng-app="app">
<div ng-controller="ctrl">
<selectpicker data-array="users" data-selected="info.selected"></selectpicker>
<button ng-click="add()">Add</button>
</div>
</div>
JS:
var app = angular.module('app', []);
app.controller('ctrl', ['$scope', function($scope)
{
$scope.info = {selected: 1};
$scope.users=[];
$scope.users.splice(0);
$scope.users = [{name: "Bob", id: "1"},{name:"Tom", id: "2"}];
$scope.add = function () {
$scope.users.push({name: "John", id: "3"});
};
}]);
app.directive('selectpicker', function($timeout)
{
return {
restrict: 'E',
replace:true,
scope: {
selected: '=',
array: '=',
class: '='
},
template: '<select class="selectpicker" multiple data-selected-text-format="count" ng-model="currentName" ng-options="user.name for user in array">' +
'</select>',
replace:true,
link: function(scope, el, attrs) {
$timeout(function () {
scope.$watch('array', function (newVal) {
console.log(scope.array);
var select = $(el).selectpicker();
select.change(function(evt) {
var val = $(el).selectpicker('val');
$scope.selected = val;
$scope.$apply();
});
}, true);
});
}
};
});
所以当我点击Add按钮时,我可以看到scope.array值
从控制台输出更新,但下拉列表本身不会更新。我试过拼凑出类似答案的解决方案,但到目前为止还没有结果。
答案 0 :(得分:0)
根据the documentation of Bootstrap-select,您可以使用refresh()
方法在基础选择标记更改时更新UI:
$(el).selectpicker('refresh');
但让我们进一步了解如何改进指令:
el
已经是一个jQuery对象,不需要再将它包装为$(el)
。$timeout
变得不必要。$watch
,否则每次更改都会多次触发处理程序。$watchCollection
就足够了,即不会更改单个选项。最终结果如下:
link: function(scope, el, attrs) {
var select = el.selectpicker();
select.change(function (evt) {
scope.selected = el.selectpicker('val');
scope.$apply();
});
scope.$watchCollection('array', function(newVal) {
console.log(scope.array);
el.selectpicker('refresh');
});
}
示例Plunker: http://plnkr.co/edit/Kt0V0UBuHaRYMjKbI5Ov?p=preview