ng-repeat displaying an empty list

Currently, I am working on an AngularJS application where I am attempting to display data retrieved using the http get method from a RESTServer.

The GET request is sent from one view and upon success, it navigates to another view within AngularJS. Both views share the same controller and I have an object in my scope variable that I am trying to iterate through. Below is my controller:

controller.js

function searchCtrl($state, $scope, $http){
    $scope.search;
    $scope.responses = [];

    $scope.submit = function(){
        if($scope.text){
            $http.get("../backend/index.php/user/searchResult?search=" + $scope.text)
                .then(function successCallback(response) {
                    $scope.responses = angular.fromJson(response.data.data);
                    console.log(typeof($scope.responses));
                    $state.go('home.search');
                });
        }
    };
    console.log($scope.responses);
}

Now, let's take a look at the view from which I am sending the request:

view1.html

<div class="row border-bottom">
<nav class="navbar navbar-static-top" role="navigation" style="margin-bottom: 0">
    <div class="navbar-header">
        <span minimaliza-sidebar></span>
        <form role="search" class="navbar-form-custom" ng-submit="submit()" ng-controller="searchCtrl">
            <div class="form-group">
                <input type="text" placeholder="SEARCH" class="form-control" name="top-search" id="top-search" ng-model="text">
            </div>
        </form>
    </div>
    <ul class="nav navbar-top-links navbar-right">
        <li>
            <a ui-sref="login">
                <i class="fa fa-sign-out"></i> Log Out
            </a>
        </li>
        <li>
            <a ng-click="$root.rightSidebar = !$root.rightSidebar">
                <i class="fa fa-tasks"></i>
            </a>
        </li>
    </ul>

</nav>

Next, here is the view receiving the data (view2.html):

view2.html

<div class="wrapper wrapper-content animated fadeInRight" ng-controller="searchCtrl">
<div class="row">
    <div class="col-lg-12">
        <div class="ibox float-e-margins">
            <div class="ibox-content">
                <h2>
                    2,160 results found for: <span class="text-navy" ng-model="search">{{search}}</span>
                </h2>
                <small>Request time (0.23 seconds)</small>
            </div>
        </div>

        <div class="ibox float-e-margins">
            <div class="ibox-title">
                <h3>Media</h3>
            </div>
            <div class="ibox-content">
                <table id="search_result1" class="display table table-striped table-responsive" cellspacing="0" width="100%">
                  <thead>
                        <tr>
                            <th>Title</th>
                            <th>Subtitle</th>
                            <th>ISBN</th>
                            <th>Reg. No.</th>
                            <th>Archive Location</th>
                            <th>Publishers</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="response in responses">
                            <td>{{response}}</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

If anyone could offer insight into why this issue is occurring, it would be greatly appreciated. This code represents only the portion relevant to the problem I am facing.

Answer №1

One possible issue could be with $state.go('home.search');. It seems like your controller is being reset. To solve this, try passing the object to

$state.go('home.search', {obj: responses});
. Then in your new view, you can access the same object as both are part of the same controller.

controller('SameCtrl', function ($state, $scope) {
    $scope.yourFunction = function (obj) {
        $state.go("hom.search", {object: JSON.stringify(obj)});
    }
})
.controller('SameCtrl', function ($state, $scope, $stateParams) {
    if(!$state.params){
        console.log(JSON.parse($state.params.object));
    }
})

Answer №2

My approach to solving this issue involved utilizing $stateParams and separating my two views into distinct controllers. While it may have been possible to achieve the same result with shared controllers, I believe that the primary purpose of $stateParams is to facilitate data communication between views, suggesting that separate controllers are recommended for this task.

Below is an excerpt from my controller.js:

function MainCtrl($state, $scope) {

  $scope.transportSearch = function(searchString){
        $state.go('home.search', {searchString: searchString });
        console.log(searchString);
    };
}

function SearchCtrl($state, $scope, $http, $stateParams){

    $scope.search;
    $scope.responses = [];
    var searchString = $stateParams.searchString;
    console.log(searchString);  

    $scope.getSearch = function(){

            $http.get("../backend/index.php/user/searchResult?search=" + searchString)
                    .then(function successCallback (response) {

                    $scope.responses = angular.fromJson(response.data.data);

            })

    };
    $scope.getSearch();
}

Lastly, here is an excerpt from my config.js, showcasing how I passed data from MainCtrl to SearchCtrl via the URL:

.state('home.search', {
            url: "/search/:searchString",
            templateUrl: "views/search_results.html",
            data: { pageTitle: 'Search' },
            controller: 'SearchCtrl'
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for a user to modify the JavaScript code on a website?

As I develop a website that heavily relies on JavaScript, I am curious about the possibility of users being able to edit the JS code themselves. For instance, if I have an ajax function that calls a.php, could a user modify the function using Firebug or a ...

Modifying the hue of Material UI tab label

I attempted to modify the label color of a tab to black, but it seems to be stuck as white. Is this color hard-coded in material-ui? If not, how can I change it? Here's what I've tried: const customStyles = { tab: { padding: '2p ...

Discovering, storing, and displaying JSON data in JavaScript

I am currently working on a PHP file called rows2.php that displays results from a database by showing the new id of the field in this format: {'new_id':'92'} My goal is to use JavaScript to load this data and add the new_id surrounded ...

Step-by-step guide to building multiple layouts in React.js using react-router-dom

For my new web application, I am looking to create two distinct layouts based on the user type. If the user is an admin, they should see the dashboard layout, while employees should be directed to the form layout. Initially, only the login page will be dis ...

When decoding a JWT, it may return the value of "[object Object]"

Having some trouble decoding a JSON web token that's being sent to my REST API server. I can't seem to access the _id property within the web token. Below is the code I'm currently using: jwt.verify(token, process.env.TOKEN_SECRET, { comp ...

Having trouble with installing a React app using npx create-react-app my-app?

description needed for image Having trouble creating a react application using npx create-react-app my-app... Encountering errors shown in the image. Attempted npm init but it was unsuccessful. Included node.js and vs code in the path. ...

Encountering an issue in Laravel when trying to retrieve data using relationships and the paginate() method

When I try to fetch data using paginate(10), Vue.js does not work. However, if I use paginate(5), it works fine. The code in the Controller with relationships in the model files is working fine and returns a 200 OK response. $results = Posts::with([' ...

Implementing multiple conditions in ng-class for dynamic styling

Is there a way to make both && and || operators work in a single expression like the example below? ng-class = "{'class_name' : condition1 || condition2 || (condition3 && condition4)}" If it is possible, then how can it be implemented? ...

Exploring the various methods of creating controllers and services in AngularJS and understanding the rationale behind each approach

I've been observing various instances of controller and service creation in AngularJS and I'm feeling perplexed. Could someone elucidate the distinctions between these two methods? app.service('reverseService', function() { this.re ...

Adding information to an HTML table using JQuery

Is there a way to incorporate JSON data into an HTML table? The JSON data follows this format: https://i.stack.imgur.com/lzdZg.png This is the desired HTML table structure: <table class="table table-bordered table-hover "> ...

The XMLHttpRequest() function throws NS_ERROR_FAILURE when sending requests to localhost using either an absolute or relative path

Encountering an error in Firefox 31 ESR: Error: NS_ERROR_FAILURE: Source file: http://localhost/Example/scripts/index.js Line: 18 Similar issue observed on Internet Explorer 11: SCRIPT5022: InvalidStateError The script used for AJAX function call i ...

The issue with the jQuery click event arises when utilizing the "Module Pattern"

Exploring the Module Pattern as described by Chris Coyyer here, I, an intermediate front-end JS developer, have encountered a problem. Specifically, when attempting to utilize a jQuery selector stored in the settings object, I am unable to trigger a click ...

Obtain a nested array of objects from Mongoose's Model.find() method and then make modifications to the inner array

I need to retrieve an array of objects with a specific ID from my database within a server route, and then update a property of an object within that array (rather than returning just the objectID, I want to return the Document as an object with the specif ...

What is the best way to use checkboxes to highlight table rows in Jquery Mobile?

I have a Jquery Mobile site with a table. Each table row contains checkboxes in the first cell. I am trying to achieve the following: a) Highlight a row when the user clicks on it b) Highlight a row when the user checks the checkbox I have made progr ...

What is the best way to pass only the second parameter to a function in TypeScript?

Let's consider a TypeScript function as shown below: openMultipleAddFormModal(commission?: Commission, people?: People): void { // some data } To make a parameter optional, I have added the Optional Chaining operator. Now, how can I modify the code ...

"Exploring the realms of AngularJS through callback functions and variable scopes

I am currently experiencing an issue with JavaScript in general. Specifically, I am trying to update a list after invoking a callback from two separate files. Here is the description of the callback : this.modify = function(){ var self = this; v ...

Instructions for saving a binary file on the client using jQuery's .post function

I am working with a handler that has the following code: HttpRequest request = context.Request; HttpResponse response = context.Response; if (request["Type"] != null) { try { string resultFile = null; ...

How can we eliminate all elements from jQuery except for the first and second elements?

HTML <div class="geo_select"> <h3>header 3</h3> in Above HTML code i want to remove all element except <h3> and default content<div> inside the <div class='geo_select'> in jquery.. How to remove all ...

How can the event listener be utilized with md-autocomplete?

I am currently in the process of developing an angularjs application that incorporates an autocomplete feature. One key aspect of this application is that certain fields cannot be populated until an item has been selected using the autocomplete function. ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...