Search code examples
angularjsui-selectui-select2angular-ui-select

angular ui-select2 not set value in edit mode


<select id="e1" style="width:100%" ui-select2  tabindex="-1" ng-init="GetAllAgent()" ng-model="Agent" ng-options="ctr as ctr.AgentName for ctr in ListAgent track by ctr.AgentId" ng-change="GetSubAgentList(Agent.AgentId)">
<option value=""> </option></select>

when it is in edit mode,could not set the default value using the below code

 angular.forEach($scope.ListAgent, function (value, index) {            
            if (value.AgentId == HR.AgentId) {
                $scope.Agent = $scope.ListAgent[index];
            }
        })

 $scope.ListAgent= [{ AgentId: "0", AgentName:"Ann" }, {  AgentId: "1", AgentName:"Muh" }];

and

HR.AgentId=1

Solution

  • First off, ui-select2 does not support ng-options: https://github.com/angular-ui/ui-select2/issues/252

    Further, ui-select2 does not work with ng-repeat: https://github.com/angular-ui/ui-select2/issues/162

    The solution is to use input:

     <input ui-select2="select2Options" ng-model="Agent"/>
    

    where select2Options is:

    $scope.select2Options = {
      data:$scope.ListAgent
    }
    

    The list should have structure: [{id,text}] so $scope.ListAgent will be

     $scope.ListAgent= [{ id:0, text:"Ann" }, { id:1, text:"Muh" }];
    

    Demo Plunker


    For place holder add data-placeholder="----"