如何在Angular中为multiselect select标记设置多个默认值

时间:2015-07-30 15:15:09

标签: javascript angularjs multi-select

如何在Angular中为多选选择标记设置多个默认值?这是我的标签:

 <select multiple="multiple"
            class="form-control multiselect"
            ng-model="dog.Tags"
            ng-options="tag as tag.Name for tag in tagsAvailable">
 </select>

我在我的控制器中调用的服务中有一个ajax调用,它返回Dog对象。 Dog对象看起来像:

{ID: 1, Name: "Lassie", Tags: [{TagID: 2, Name: "Red"},{TagID: 3, Name: "Barker"}]}  

这是我的控制器中调用返回Dog JSON对象的服务的方法。

dogSvc.getDog($routeParams.dogId).then(
            function (response) {
               $scope.dog = response.data;
            },
           function (response) {
               $scope.status = response.status;
       });

我想将默认选择的值设置为Dog.Tags值。

然后我有一个类似的服务返回所有可用的标签,我想在选择框中填充选项。

tagSvc.getAllTags().then(
    function (response) {
        $scope.tagsAvailable = response.data;
    },
    function (response) {
        $scope.status = response.status;
    });

填充可用标记,但不填充默认值。如何根据我返回的Dog对象的标签预选选项?

1 个答案:

答案 0 :(得分:0)

这就是我最终做的事情

$q.all([tagSvc.getAllTags(), dogSvc.getDog($routeParams.dogId)]).then(
    function (responses) {
        $scope.tagsAvailable = responses[0].data;
        $scope.dog = responses[1].data;
        $scope.dog.Tags = $scope.tagsAvailable.filter(
                 function (tag) {
                     return $scope.dog.Tags.some(
                         function (elem) {
                             if (elem.TagID == tag.TagID) return true;
                         });
                 });

    });

基本上这个:

  1. 检索可用的标签。
  2. 检索现有标记,这将成为默认标记。
  3. 获取可用标记并对其进行过滤,以便仅包含现有标记数组中存在的可用标记。
  4. 将过滤的可用标记设置为模型的标记值。