Search code examples
javascriptangularjsjsonangularjs-ng-options

Error resolving my dynamic json compared to hardcoded json in ng-options


I have a listbox and I'm binding a list of item from a controller.

$scope.AvailableListItems = [
    [{Id:1,SupplierName: 'john.banks'},
    {Id: 2,SupplierName: 'jim.chevy'}, 
    {Id: 3,SupplierName: 'ralph.stocks'}]
];

This is hardcoded json. When I try this with below html it is working absolutely fine

<select multiple id="availabelist" size="10" style="width:100%" ng-change="OnAvailableChange()" ng-model="SelectedAvailItems" ng-options="i as i.email for i in AvailableListItems[selectFaIndex]| filter:availablequery"></select>

But, when I try to generate the same thing dynamically, then its not working at all. Getting a blank list box. Code is as below.

 var getSuppliers = function () {  
            var tempArray = [];
            var lstsuppliers = CRUDService.getApiOutput(getSuppliersApiRoute);
            lstsuppliers.then(
                function (response) {
                    debugger;
                    $scope.supplierList = response.data;
                    for (var i = 0; i < $scope.supplierList.length; i++) {
                        arr = {};
                        arr["Id"] = $scope.supplierList[i].supplierId;
                        arr["SupplierName"] = $scope.supplierList[i].supplierName;
                        tempArray.push(arr);
                    }
                    $scope.AvailableListItems = tempArray;
                    console.log(JSON.stringify($scope.AvailableListItems));
                },
                function (error) {
                    console.log("Error: " + error);
                });
}

Please help me find the problem in my code.

Working Plunk link

This is how my response data looks like: Updated based on Claies enter image description here

[{"Id":1,"SupplierName":"ACECO PRECISION MANUFACTURING"},{"Id":2,"SupplierName":"Pentagon EMS Corporation"},{"Id":3,"SupplierName":"QUANTUMCLEAN"},{"Id":4,"SupplierName":"MODERN CERAMICS"},{"Id":5,"SupplierName":"NXEDGE INC"}]

Solution

  • After breaking for hours together, finally found the solution. I have put both hardcoded and dynamic values together to console. and i found below difference. enter image description here

    I modified

    $scope.AvailableListItems = tempArray;
    

    to

    $scope.AvailableListItems.push(tempArray);
    

    in line no.14, and it worked. The output is like this after i changed the code enter image description here

    Thanks for @Tomas and @Claies specifically.