Angularjs reset to default option with ngOption

Asked

Viewed 147 times

0

When activating the addAgent method 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"},
];

1 answer

0


You declared the variable $scope.agents as an Array? I copied your code to Plunker and the only change I made was declaring 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

  • your plunker is not complete.

  • @Celsomtrindade tests now. Thank you for warning.

  • Just to get a better view of https://plnkr.co/edit/eO3qJk0T4MZGFzBSddeL?p=preview but really, if the solution was just to add $Scope.Agents, perfect =D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.