Dynamically populated option select list selected with Angularjs

Asked

Viewed 2,702 times

2

I need to bring one select option with the selected option being filled dynamically.

I have in my controller the filling of the list so:

$scope.$watch('IdCategoria', function() {
            $http.get("/api/Categoria/GetList", {  }).success(function(response) {
                $scope.categorias = response;
            });
        });

And mine select is like this:

<select ng-model="newCtrl.IdCategoria" required class="form-control" data-live-search="true" ng-options="c.Value as c.Text for c in categorias">
<option value="">Selecione uma categoria</option>
</select>

Where the newCtrl.IdCategoria is the field with the Id of the selected category, in which the select should come selected.

I read here on Stack that using the track by should work, but if I set track by newCtrl.IdCategoria, both in editing and registration I can not perform the selection of another option.

I’ve tried using the ng-init, but also without success:

ng-init="newCtrl.IdCategoria= newCtrl.categorias[newCtrl.IdCategoria]"

Remembering that my categories are:

[{"Value":"24","Text":"Categoria 1"},{"Value":"25","Text":"Categoria 2"}]

EDIT1 I’ve tested it like this

<select ng-model="newCtrl.IdCategoria" required class="form-control" data-live-search="true">
<option value="">Selecione uma categoria</option>
<option ng-repeat="c in categorias" value="{{c.Value}}">{{c.Text}}</option>
</select>
  • Have you looked at documentation?

  • Yes... I don’t know if it’s because of the dynamic information but it doesn’t work at all.. I’ve even tried using ng-repeat no options and nothing!

3 answers

1

Inside of your controller:

$scope.$watch('IdCategoria', function() {
            $http.get("/api/Categoria/GetList", {  })
            .success(function(response) {
                if (response.length > 0) {
                     response.unshift({"Value":"0", "Text":"Selecione uma categoria"});
                   $scope.categorias = {
                                         availableOptions: response,
                                         selectedOption: {
                                             Value: response[0].Value,
                                             Text: response[0].Text
                                        }
                                    };
               }
            });
        });

Then in view:

<div ng-controller="newCtrl as ctrl">

   <select name="selecao" class="form-control" id="selecao" required class="form-control" data-live-search="true"
      ng-options="option.Text for option in ctrl.categorias.availableOptions track by option.Value"
      ng-model="ctrl.categorias.selectedOption"></select>

Remembering that this will only happen if there is an interaction in this element "Idcategoria" that I have no idea what is and where you are interacting it, because the $watch function is to listen to the element, when it is changed:

Take an example:

angular
  .module('seuApp', [])
  .controller('ACtrl', function ($scope) {
    $scope.collection = [];
  })
  .controller('BCtrl', function ($scope) {
    $scope.$watch('nome.input', function (newValue, oldValue) {
         console.log('escutando elemento, valos novo: ' + newValue);
    });
  });

And in HTML:

  <html ng-app="seuApp">
      <body ng-controller="ACtrl">
        <div ng-repeat="(key, nome) in collection" ng-controller="BCtrl">
          Nome {{key}}: <input ng-model="nome.input" ng-change="doSomething()">
          <br />
         Olá seu nome é {{ nome.input }}
        </div>
        <button ng-click="collection.push([])">Incluir nome</button>
      </body>
    </html>

Look at the JSFIDDLE (1) and JSFIDDLE (2)

  • Good morning Ivan, then.. It didn’t work out, for the following reason. on the line where you define the selectionOption[0] indicating that the selected one is the Dice 0 of the list, hence it brings the first selected item instead of selecting the item that came from the base on which I inform here in my ng-model='newCtrl.Idcategory'

0

Ivan,

Your json is coming value as a string, check whether your Idcategory is a string or an integer, if they are of incompatible types you will either have to change your service and bring values of the same types, or change in the interface using a toString or parseint, the most correct way is to change the service, after that the second option you tried value="{c.Value}}" should work.

Worth a look also here:

https://docs.angularjs.org/api/ng/directive/ngSelected

0

Try this

<select ng-model="newCtrl.IdCategoria" required class="form-control" data-live-search="true" ng-options="c.Value as c.Text for c in categorias">
<option value="">{{newCtrl.IdCategoria ? newCtrl.IdCategoria : "Selecione uma categoria"}}</option>
</select>

can work if the newCtrl.Idcategoria not empty if empty appears Select a category

Browser other questions tagged

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