AngularJS Display JSON data in view

40 Views Asked by At

In my module I have a service that calls $http and gets an Array of objects,

function MenuSearchService($http){       
        this.getMatchedMenuItems=function(searchItem){
             var foundItems =$http({
                method:'GET',
                url:'https://whateverurl.com/whateverdata'
            });
            return foundItems;
        }; // end function
    }; // end service

and I use a controller (as a syntax) to process the data,

function MenuController(MenuSearchService){
        this.query;
        this.results;
        this.promise;
        this.searchClicked=false;
        this.clickToSearch = function(searchItem){
            this.searchClicked=true;
            this.query=searchItem;
            this.promise=MenuSearchService.getMatchedMenuItems()
            .then(function(result){
                this.foundItems = result.data;
                console.log(this.foundItems);        
                }); 
        }; // end onclick
    }; // end controller

I am able to retrieve the data. Here is the stdout of foundItems:

enter image description here

Each object in the foundItems has properties name and description.But when I want to present it in the view,

<section class="container" ng-controller="MenuController as m">
    <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="item in m.foundItems">               
                        <td>{{item.name}}</td>
                        <td>{{item.description}}</td>
                    </tr>
                </tbody>
            </table>
</section>

the data is not shown. Can anyone tell what goes wrong?


Update After taking a look at @charlietfl's comment I updated my code to:

function MenuController(MenuSearchService){
        var m=this;
        m.query;
        m.promise;
        m.searchClicked=false;
        m.clickToSearch = function(searchItem){
            m.searchClicked=true;
            m.query=searchItem;
            m.promise=MenuSearchService.getMatchedMenuItems()
                .then(function(result){
                        m.foundItems = result.data;                       
                        console.log(m.foundItems);  

                    }).catch(function (error) {
                        console.log(error.message());
                });
            }; // end onclick
        }; // end controller

The concept is wrongly using this. in a function inside a controller.

0

There are 0 best solutions below