我在我的Angular项目中使用select2,实际上我有一个问题,那就是我不知道如何设置select-option的默认值。下面是我的代码:
HTML:<select-tag-manager parent-id="2" value="restaurant.type" ></select-tag-manager>
角:
app.directive('selectTagManager', function() {
return {
restrict: "E",
replace: true,
scope: {
parentId: '@',
value: '='
},
controller: function($rootScope, $scope, Gateway, toaster, $element, Tags) {
var element;
$scope.update = function () {
};
var makeStandardValue = function(value) {
var result = [];
angular.forEach(value , function(tag , key) {
if(result.indexOf(tag.tagId) < 0) {
result.push(tag.tagId);
}
});
return result;
};
var init = function () {
Gateway.get('', '/tag?' + 'parentId=' + $scope.parentId, function(response) {
$scope.allPossibleTags = response.data.result.tags;
});
element = $($element).children().find('select').select2();
console.log(element);
};
$scope.$watch('value', function(newval) {
if( newval ) {
$scope.standardValue = [];
angular.forEach(newval, function(val, key) {
$scope.standardValue.push(val.tagName);
});
console.log($scope.standardValue);
}
});
init();
},
templateUrl: 'selectTagManager.html'
}
});
selectTagManager.html:
<div class="row">
<div class="col-md-12">
{{ standardValue }}
<select class="select2" multiple="multiple" ng-model="standardValue" ng-change="update()">
<option ng-if="tag.tagId" ng-repeat="tag in allPossibleTags" data-id="{{tag.tagId}}" value="{{tag.tagId}}">{{ tag.tagName }}</option>
</select>
</div>
</div>
I got value
console.log($scope.standardValue);
result: ["lazzania", "pizza", "kebab"]
但是我不知道如何将它们设置为选择选项中的默认值。任何建议吗?
编辑:我刚刚用Angular-ui/ui-select2编辑了我的问题。我改变了我的模板:
<select ui-select2 = "{ allowClear : true }" ng-model="standardValue" multiple="multiple" >
<option value="standardId" ></option>
<option ng-repeat="tag in allPossibleTags" value="{{tag.tagId}}">{{tag.tagName}}</option>
</select>
还有js:
$scope.$watch('value', function(newval) {
if( newval ) {
$scope.standardValue = [];
$scope.standardId = [];
// $scope.standardValue = makeStandardValue(newval);
console.log('----------------------------------------------------------------------');
angular.forEach(newval, function(val, key) {
$scope.standardValue.push(val.tagName);
$scope.standardId.push(val.tagId);
});
console.log($scope.standardValue);
console.log($scope.standardId);
}
});
然而,我仍然不能设置默认值
正如在http://select2.github.io/examples.html#programmatic演示的那样,可以为多个select2元素设置默认值,如下所示:
$exampleMulti.val(["CA", "AL"]).trigger("change");
如果你已经有了指向select2的元素变量:
element.val($scope.standardValue).trigger('change');
注意,这是jQuery设置/更改值的方法,angular的方法是通过ng模型和它的生命周期事件来更新值
模型中的id需要与数据源中的id匹配,因此,如果您的模型为:
["lazzania", "pizza", "kebab"]
那么allPossibleTags
需要看起来像:
[{ tagId: "lazzania", tagName: "Lazzania" }, { tagId: "pizza" ...
查看下面的示例:
http://plnkr.co/edit/e4kJgrc69u6d3y2CbECp?p =预览