Search code examples
angularjsjsonangularjs-ng-repeatgetjson

Populate a select list with AngularJS from a response in JSON


I would like to download a response on a server in JSON which contains the attribute to populate my select list. I would like to do it with AngularJS and I'm using Angular 2. Nothing appears, I think the problem is on my attribute ng-repeat :

<div id="myDiv">

  <div ng-app="d3DemoApp">
    <div ng-controller="AppCtrl">
      <div ng-repeat="n in filters track by $index">
        {{n}}
       </div>
     </div>
  </div>

</div>

This is my controller :

angular.module('d3DemoApp',[])
    .controller('myCtrl',function($scope) {
        $scope.notes = userService.getData();
        //Create and append select list
        var selectList = document.createElement("select");
        selectList.setAttribute("id", "releaseFilter");
        myDiv.appendChild(selectList);
        selectList.setAttribute("class", "form-control");
        selectList.setAttribute("onclick", "myFunction()");

        //Create and append the options
        for (var i = 0; i < $scope.notes.length; i++) {
            var option = document.createElement("option");
            option.setAttribute("value", array[i]);
            option.text = $scope.notes[i];
            selectList.appendChild(option);
        }
});

This is the service which should download the response :

app.service("userService",["$http",
    function($http) {
        _this = this;
        this.getData = function() {
        },
            $http.get('./dataOnServer.json'). // This adress is normally an HTTP adress which send me the JSON
            success(function(data) {
                return data;
            });
    }
]);

This is an online example of the problem with Plunker : https://plnkr.co/edit/du7sU8bhg2G3X7HckbV9?p=preview

I hope you will can help me, thanks a lot !


Solution

  • I would point out that you are repeating filters when you are not defining such variable in your scope or anywhere? You should probably repeat $scope.notes so it would go like this:

    <div id="myDiv">
      <div ng-app="d3DemoApp">
        <div ng-controller="AppCtrl">
          <div ng-repeat="n in notes track by $index">
            {{n}}
          </div>
        </div>
      </div>
    </div>
    

    EDIT:

    And you can do a select like this:

    <select>
      <option ng-repeat="n in notes">{{n.value}}</option>
    </select>
    

    And your JSON is invalid. It should be like this for the repeat:

    [{value: "value 1"},{value: "value 2"},{value: "value 3"}]