Refresh the ng-repeat directive in Angular/Ionic

After reading several discussions on this issue, none of the suggested solutions seem to work for me.

The first approach I took was with a controller:

.controller('TestFriendCtrl', ['$scope', 'APIUser', function($scope, APIUser) {

        $scope.data.friends = [{username: 'test'}];

        $scope.change = function(friend) {
            APIUser.find(friend, function(success, data){
                if (success) {
                    $scope.data.friends = data;
                    console.log($scope.data.friends);
                }
            })
        }
    }]);

I also attempted another method:

.controller('TestFriendCtrl', ['$scope', '$timeout', 'APIUser', function($scope, $timeout, APIUser) {

    $scope.friends = [{username: 'coucou'}];

    $scope.change = function(friend) {
        APIUser.find(friend, function(success, data){
            if (success) {
                $timeout(function() {
                    $scope.friends = data;
                    console.log($scope.friends);
                } );
            }
        })
        console.log($scope.friends);
    }
}]);

Last but not least, I tried one more option:

.controller('TestFriendCtrl', ['$scope', '$timeout', 'APIUser', function($scope, $timeout, APIUser) {

    $scope.friends = [{username: 'coucou'}];

    $scope.change = function(friend) {
        APIUser.find(friend, function(success, data){
            if (success) {
                $scope.friends = angular.copy(data);
            }
        })
        console.log($scope.friends);
    }
}]);

Despite all these attempts, when using console.log($scope.friends);, the output is as expected.

In addition to the controller setup, there's also a view:

<ion-view class="main-page">
    <ion-content>
        <h1>Friend</h1>
        <label class="item item-input">
            <i class="icon ion-search placeholder-icon"></i>
            <input ng-model="friend" name="friend" type="search" placeholder="Search" ng-change="change(friend)">
        </label>
        {{ data.friends[0].username }}
        <ion-list ng-controller="TestFriendCtrl" >
            <ion-item ng-repeat="friend in data.friends" class="item-thumbnail-left">
                <p>{{friend.username}}</p>
            </ion-item>
        </ion-list>
    </ion-content>
</ion-view>

While the $scope.friend value updates correctly in the console, the list remains unchanged on the view.

Attempts to resolve this included adding $scope.$apply, which resulted in an error message stating $digest already in progress.

Answer №1

Have you thought about giving this a shot? I'm not entirely sure what the APIUser function does:

.controller('TestFriendCtrl', ['$scope', 'APIUser', function($scope, APIUser) {
    $scope.friends = [{username: 'test'}];

    $scope.change = function(friend) {
        APIUser.find(friend).$promise.then(function(success, data){
            if (success) {
                $scope.friends = data;
                console.log($scope.friends);
            }
        }, function (err) {
            console.log(err);
        )};
    }
}]);

Answer №2

After reviewing your most recent update, it seems like there could be a link to the "dot." Numerous posts can be found on Google explaining why it is not advisable to have a direct model without a dot delimiter.

I recommend updating your model with $scope.myDatas.friends = data; and adjusting your ng-repeat call to

ng-repeat="friend in myDatas.friends"

Answer №3

The suggestion made about using angular.copy() was close to being correct, but it overlooked the importance of the second parameter. By utilizing angular.copy() (or the similar Lodash's _.assign()), you can avoid losing the reference to the original array instance. Take a look at this explanation or this answer for more details.

.controller('TestFriendCtrl', ['$scope', 'APIUser', function($scope, APIUser) {
    $scope.friends = [{username: 'test'}];

    $scope.change = function(friend) {
        APIUser.find(friend).$promise.then(function(success, data){
            if (success) {
                angular.copy(data, $scope.friends);
                console.log($scope.friends);
            }
        }, function (err) {
            console.log(err);
        )};
    }
}]);

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

What is the reasoning behind the React tutorial's suggestion to store child Component states within the parent Component?

As stated in the React tutorial found on this link: The tutorial suggests that when needing to aggregate data from multiple children or enable communication between child components, it is recommended to move the state upwards into the parent component. ...

Add the $scope ng-click event to a previously hidden element once it becomes visible

If you need a clearer explanation, feel free to ask. I have incorporated a global search function into the header of my website. I am looking to show a separate input box for mobile search that utilizes the same ng-click event, but the input field remains ...

Having trouble sending data to a Laravel 5 controller through Angular. Keep getting Error 422: Unprocessable Entity

My login form is built with angularjs, and I am trying to send the user's credentials to the default AuthController in Laravel 5. However, I keep encountering a server response of 422 Unprocessable Entity with the message: email field is required. HT ...

Executing a script programmatically using an NPM package

I'm in the process of developing a package that relies on an external command tool called plop js. In my package.json, I aim to include a binary that points to an index.js file. "scripts":{ "plop": "plop" }, "bin": { "my-command": "ind ...

Troubleshoot: Unable to Change CSS on Click Using Javascript/jQuery

Having trouble creating three different buttons that toggle between various images using the CSS display property? Check out my code on https://jsfiddle.net/agt559e8/. function USradarChange1() { //document.getElementById("usradar1").src="weather/curr ...

Is it possible to update my services list based on which checkboxes I choose to uncheck at the top?

i am currently tackling a small project, and I have limited experience with javascript and json. Can someone assist me in resolving the final step? I am on the verge of completing it, but encountering some issues. My goal is to filter the results based on ...

The Chip Component in MUI dynamically alters its background color when it is selected

Currently, I am working on a project in React where I am utilizing the MUI's Chip component. My goal is to customize this component so that it changes its background color when selected, instead of sticking to the default generic color. https://i.sta ...

Retrieve the weekday dates for a specific year, month, and relative week number using Javascript or Typescript

I am in need of a custom function called getDaysOfWeekDates that can take a year, a month (ranging from 0 to 11), and the week number of each month (usually 4-5 weeks per month) as parameters, and return a list of dates containing each day of that particul ...

Retrieve JSON data upon refreshing the page

In my blogging application, each post has its own unique permalink structure, such as /post/Dh3hdjs* where Dh3hdjs* represents the specific permalink. However, I am facing an issue where after successfully creating a post and being redirected to the specif ...

When working with ReactJS and NextJS applications, the variables declared in the .env file may sometimes be received as undefined

In my .env.local file, the following variable is defined: REACT_APP_API_PATH=http://localhost:3600/ The .env.local file can be found at the root level of the project directory. Here is how I am attempting to utilize this variable: console.log('node ...

Dealing with asynchronous requests in Axios: A guide to solving the challenge

I'm working on a page named _id.vue in my Nuxt.js project: <template> <div class="wrapper"> <HeaderApp> <DivHeaderMenu> </DivHeaderMenu> </HeaderApp> <CenterContentDinamicFirmeni ...

CSS: Hover below the designated target to reveal an expanding dropdown menu

My initial solution involved toggling the visibility on and off when hovering. However, this approach is not optimal as the menu should smoothly transition into view. When the visibility is toggled, the user does not experience the intended transition effe ...

Alter the color as the text moves beneath a see-through layer

Imagine a scenario where there is a page with text and on top of that, there is a transparent div that is smaller than the text area. Is it feasible to dynamically alter the color of the text that scrolls underneath the transparent div? Picture the trans ...

Can we switch the country name to the database name in Jvector?

I've successfully implemented the Jvectormap application and it's functioning as expected. When I click on a country, it displays the name of that country. I have established a simple database for specific countries. Through AJAX, I've conn ...

Transferring information from an Angular service to a controller

I have set up an Angular service and controller, but I am facing difficulty in passing data between the two to retrieve the value for voucher_code. Angular Service: myApp.service('tradeData', function ($http) { var service ={}; var voucher_code ...

When attempting to send data from Ajax to PHP as JSON, an error occurs and the data transmission fails

When attempting to send data as JSON, an error response is received stating: SyntaxError: Unexpected token < in JSON at position 0. If the data is sent as text, it successfully reaches PHP, but PHP does not respond accordingly. AJAX/JavaScript using J ...

Can someone explain how to iterate through an array to find a specific value using CoffeeScript?

Having trouble extracting the full_name value from an array using CoffeeScript. Despite extensive research on Stack Overflow and CoffeeScript's docs, I haven't been able to solve it. Here is my current code. Can someone help me identify what&apos ...

personalized options for initiating and concluding html audio component

I am currently facing an issue with my html audio element that plays a track. The setup is quite straightforward: <audio controls loop="loop"> <source type="audio/wav" src="song.wav"> </audio> However, I need to create custom start ...

Dynamic popup in RShiny interface with the ability to be moved around

I am currently working on a dashboard project and I am looking to implement a dynamic popup feature that can be moved around. I have been able to create a pop-up, but it remains static. I would like the flexibility for users to drag and position the popup ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...