【问题标题】:Angularjs select2 set options selectedAngularjs select2 设置选项被选中
【发布时间】:2016-06-03 07:20:51
【问题描述】:

我想在用户点击 html 按钮时构建选择列表 (select2) 选项。

我的 HTML:

<select id="mySel2" class="form-control" multiple="multiple">
    <option ng-repeat="item in items" ng-selected="item.selected"
            ng-model="item.tag">
      {{item.tag}}
    </option>
</select>

按钮点击的Angular js函数代码:

var fruits=angular.module("myApp",[]);
fruits.controller('ctrlTags',  function($scope){

  /* I HAVE SET DEFAULT VALUE TO SELECT LIST*/
  /* IT WORKING PERFECT WITH SHOWING SELECTED VALUES*/
    var tagsData = [
      {id:1,tag:'Apple'},
      {id:2,tag:'Banana'},
      {id:3,tag:'Cherry'},
      {id:4,tag:'Cantelope'},
      {id:5,tag:'Grapefruit'},
      {id:6,tag:'Grapes',selected:true},
      {id:7,tag:'Lemon'},
      {id:8,tag:'Lime'},
      {id:9,tag:'Melon',selected:true},
      {id:10,tag:'Orange'},
      {id:11,tag:'Strawberry'},
      {id:11,tag:'Watermelon'}
    ];  

     $scope.items = tagsData;

     /*NOW ON BUTTON CLICK GETKEY() FUNCTION WILL BE CALLED*/
     /* AND I WANT TO RENDER/REFRESH SELECT LIST WITH NEW DATA */
     $scope.getKey=function(data){   
         var newData = [
          {id:4,tag:'car'},
          {id:5,tag:'bat',selected:true},
          {id:6,tag:'cat',selected:true},
          {id:7,tag:'Lemon'},
          {id:8,tag:'Lime'},

        ];
    $scope.items=newData;

    };
}); 

问题:单击按钮正在更新选择列表值,但不显示默认选择值

请告诉我如何刷新选定的值。

【问题讨论】:

  • ng-model 不应该放在option 元素上,应该放在select 上,也应该有不同的名称
  • 代码仍然可以正常工作。但只有从 ng-click 设置选定值的问题。

标签: angularjs jquery-select2


【解决方案1】:

使用select2 (form-widgets.js)

$('[name="NAME"]').select2({placeholder: ''}).val(VAL).change();

【讨论】:

    【解决方案2】:

    您需要将模型添加到选择部分 ng-model="selected"。 例如,您可以添加第一个索引 在控制器 $scope.selected = tagsData[0]

    【讨论】:

    • 它正在处理初始加载。但是单击按钮时不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2021-01-24
    相关资源
    最近更新 更多