AngularJs reset to default option with ngOption

0

When the addAgent method is triggered the item is added but the selected option continues and the default option should be selected again.

Controller

$scope.addAgent = function (selectedAgent) {

    if (null == selectedAgent) {
        alert('Selecione um Agente para adicionar.');
        return;
    }

    $scope.agents.push(selectedAgent);
    //mesmo resetando aqui, o último option selecionado continua marcado
    $scope.selectedAgent = '';
};

View

<label>Agentes</label>
 <select class="form-control" 
        ng-model="selectedAgent"
        ng-options="option as option.name 
        group by option.type for option in availableAgents track by option.id">

<option value="" ng-selected="selectedAgent ==''">Selecione</option>

</select>

<a ng-click="addAgent(selectedAgent)" 
 class="btn btn-sm btn-success" title="Adicionar Agente"><i class="fa-plus fa"></i></a>

Example ngOption data format

var availableAgents =  [
 {id:1, name:"aaaa", "type":"A"},
 {id:2, name:"aaaa2", "type":"A"},
 {id:3, name:"bbbb", "type":"B"},
];
    
asked by anonymous 14.04.2016 / 22:54

1 answer

0

Have you declared the variable $scope.agents as an Array? I copied your code to Plunker and the only change I made was to declare the variable as an Array.

Controller:

angular.module('app', []).controller('appController', function($scope) {
  $scope.agents = [];
  $scope.availableAgents = [{
    id: 1,
    name: "aaaa",
    "type": "A"
  }, {
    id: 2,
    name: "aaaa2",
    "type": "A"
  }, {
    id: 3,
    name: "bbbb",
    "type": "B"
  }, ];

  $scope.addAgent = function(selectedAgent) {
    if (null == selectedAgent) {
      alert('Selecione um Agente para adicionar.');
      return;
    }

    $scope.agents.push(selectedAgent);
    //mesmo resetando aqui, o último option selecionado continua marcado
    $scope.selectedAgent = null;


  };

})

Html:

<select class="form-control" 
        ng-model="selectedAgent"
        ng-options="option as option.name 
        group by option.type for option in availableAgents track by option.id">

<option value="" ng-selected="selectedAgent ==''">Selecione</option>

</select>

<a ng-click="addAgent(selectedAgent)" 
 class="btn btn-sm btn-success" title="Adicionar Agente"><i class="fa-plus fa"></i>Adicionar</a>

Plunker

    
15.04.2016 / 01:12