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

When I click the button, it deletes the DOM element and hides it, preventing me from

I'm facing a simple issue that I can't quite wrap my head around. Whenever I input a value into the form and click the button to run the function, the 'loading' element disappears and doesn't reappear. Here is the JavaScript code ...

Determine the item in a collection of objects that contains a specific key

What is the most efficient method for locating an object by a specific key in JS when given an array of objects? Utilizing jQuery and underscoreJS is acceptable. I am simply seeking the simplest solution with minimal code. Illustration: Suppose we have a ...

How can you set an input field to be initially read-only and then allow editing upon clicking a button using Vue.js?

//I have two divs that need to be set as readonly initially. When an edit button is clicked, I want to remove the readonly attribute and make them editable. <div> <input type="text" placeholder="<a href="/cdn-cgi/l/email-protection ...

Adjusting the properties of an element with Javascript

My goal is to dynamically set the value of a parameter within a <script> element using JavaScript. I am using the Stripe checkout.js and I want to populate the Email input field with a value obtained from another text box on the page. Here's how ...

Retrieving the ID from the element that was clicked

Here is a code snippet that allows for the changing of color and text when an href link is clicked. /* Function to change the color of the button upon click */ function changeColor(element) { alert(element.target.id); if (element.innerHTML == "Selec ...

The e.currentTarget attribute in Material UI buttons is a key element that

I am facing an issue with implementing three tabs and buttons in my project. Each button should display a corresponding message when selected I have tried using e.currentTarget but no success so far. Can someone guide me on how to resolve this problem? You ...

Dealing with PhantomJS: Tackling the Challenge of XMLHttpRequest Exception 101 Error

As a newcomer to JavaScript and PhantomJS, I have been encountering an issue when running myfile.js (which involves for loops) with the command phantomjs myfile.js. It consistently throws the error: NETWORK_ERR: XMLHttpRequest Exception 101: A network err ...

Convert the jQuery functions click(), hide(), and fadeIn() into their equivalent native JavaScript functionalities

I'm determined to speed up my page by reducing requests. Does anyone have a solution for keeping the functionality of the code below without having to load the entire JQuery library? $("#div1").click(function () { $("#div2).hide(); $("#div3). ...

Leveraging Bootstrap grid system within AngularJS elements

I am currently working on wrapping grid element divs into Angular components in order to streamline the input process and establish a standard: <bootstrap-row> <bootstrap-input-text col=6 ng-model="$ctrl.model" label="hey!"& ...

Change the order of numbering in ordered lists

I am seeking a way to change the ordering of an ordered list to be in descending order. You can view a live example here. Instead of having the counter span multiple ol elements, I would like the counter to reset after each ol. For the live demo, the des ...

Adding dynamic text to a <span> tag within a <p> element is causing a disruption in my layout

I'm encountering an issue with a Dialog box that displays a message to the user regarding file deletion. Here's how it looks: +-----------------------------------------------------------------------+ | Delete File? ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

5 Simple Steps for Adding a Value to a Popup Textbox Automatically

I want to send a value to another php page and then display the values. How can I achieve this? Here is the PHP code snippet: if(!empty($_POST["mytext"])) { for ($x=1; $x<=$a; $x++) { echo $txtLine[$x] = $_POST['mytext'.$x]; } } B ...

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...

Designing a Dynamic Floating Element that Shifts with Scroll Movement

Hey there everyone!, I am currently working on a project in Wordpress and I was wondering if anyone has experience creating a floating widget that moves along with the page as you scroll. Any suggestions on how to achieve this? Would it involve using Javas ...

"Unlock the secret to effortlessly redirecting users to a designated page when they click the browser's back

So I'm facing the challenge of disabling the browser back button on multiple routes and sending requests to the backend is resulting in inconsistent behavior. I don't want to create a multitude of similar API requests each time. Currently, I have ...

Having trouble with asynchronous JSON calls in JavaScript when setting async to false

I'm having trouble figuring out what I'm doing wrong in this scenario. The issue is that I can't seem to reassign the variable poster_path with the fetched poster-path from the JSON call. What's puzzling to me is that I even tried setti ...

New post: "Exploring the latest features in Angular

Looking for help with integrating Angular and SpringREST to fetch data from the backend? Here's my situation: I need to retrieve a JSON string from the backend using a POST request, send it to my site's hosted link, and display it on the user int ...

Is it possible to maintain a fixed footer while utilizing async/ajax functions?

Looking for a reliable solution to have a fixed footer that adjusts based on the page content? I've tested multiple samples, but they all fall short when it comes to incorporating AJAX elements. Is there a fixed footer out there that truly works seaml ...

Showing options in a menu to choose from

I'm currently working on implementing a dropdown menu for a news website. When the user selects '1' from the dropdown list, the page should display content corresponding to that selection. If the user selects '2', the page ...