Refresh ng-repeat using updated information

One of my services provides a list of available videos that can be displayed using an ng-repeat in a controller. The service function retrieves the list of videos and populates a variable within the $rootScope.

videosApp.factory('VideosService', function ($http, $rootScope) {
    $rootScope.videos = {
        list: [],
    };

    $http.get('/panel/videos')
        .then(
            function (response) {
                $rootScope.videos.list = response.data;
            },
            function () {
                alert('what is the velocity of a swallow?');
            }
        );

    return $rootScope;
});

videosApp.controller('VideosController', [
    '$scope', '$http', '$filter', '$window',
    function ($scope, $http, VideosService) {

        $scope.deleteVideo = function(id) {    
            if (confirm('Are you sure you want to delete this video?')) {
                $http.delete('/panel/videos/'+id)
                    .then(
                        function (response) {
                            growl(response.data.message, 'success');
                        },
                        function (response) {
                            growl(response.data.message, 'danger');
                        }
                    );
            }
        }

    }
]);

The HTML code displays the list of videos and includes a button for deleting each video:

<div id="videos-listing" class="row" ng-controller="VideosController">
    <ul>
        <li ng-repeat="video in videos.list">
            {{video.name}}
            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
                <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
                <li role="presentation">
                    <a role="menuitem" href="#delete" ng-click="deleteVideo(video.id)">Delete</a>
                </li>
            </ul>
        </li>
    </ul>
</div>

The challenge I'm facing is how to refresh the video listing after successfully deleting an item. One approach I considered was to call the get '/panel/videos' endpoint again after deletion, but then how do I update the ng-repeat? Are there better alternatives?

Answer №1

Here is a suggestion to try:

HTML

<a role="menuitem" href="#delete" ng-click="deleteVideo(video)">Delete</a>

JS

$scope.deleteVideo = function(video) {    
    if (confirm('Are you sure you want to delete this video?')) {
        $http.delete('/panel/videos/'+video.id)
            .then(
                function (response) {
                    growl(response.data.message, 'success');
                    $scope.videos.list.splice($scope.videos.list.indexOf(video),1);
                },
                function (response) {
                    growl(response.data.message, 'danger');
                }
            );
    }
}

Update

You may also want to explore the use of Collection helpers such as Backbone's Collections

Your code could be enhanced with the following additions:

JS:

$rootScope.videos.list = new Backbone.Collection();
$rootScope.videos.list.reset(response.data);

...
$scope.videos.list.remove(video);

HTML

<li ng-repeat="video in videos.list.models">

These enhancements provide additional functionality and features for your code ;)

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

how to show an error in a modal window when encountering an error

Using Blazor and Blazorstrap, typically when the server disconnects, an "Error" message is displayed. However, with the BsModal from Blazorstrap, it appears in the background layer, making it unresponsive. How can this be fixed? Is it possible to close the ...

Running and animating two Three-JS objects simultaneously: A step-by-step guide

I have created two 3JS objects and scenes for educational purposes. Each one is stored in separate PHP files (not in the jsfiddle). However, I'm facing an issue where adding a second object causes the first object to stop animating. How can I troubles ...

How can I redirect to a different URL when the dropdown selection changes?

<form action="myservlet.do" method="POST"> <select name="myselect" id="myselect" onchange="this.form.submit()"> <option value="1">One</option> <option value="2">Two</option> <option value="3"& ...

Babel 7 encounters an issue with a lone plugin: "Error - Plugin/preset found duplicated."

The problematic plugin is @babel/plugin-transform-regenerator, which has a high download rate of 1.6 million per week. This is the complete content of my .babelrc file: { "presets": [], "plugins": [ "@babel/plugin-transform-regenerator" ] } Wh ...

Angular: Using ng-blur to toggle visibility between elements

I'm having trouble toggling the visibility of these divs: <div class="desc" ng-show="desc"> and displaying this div <div class="lists" ng-show="lists" ng-repeat="x in todoWork | orderBy:['todoPriority', 'todoTime&ap ...

Why would someone use the `catch` method in Angular $http service when the `then` method already takes two arguments (success and error callbacks)?

When working with the Angular $http service, there is a then method that can take two arguments - one for success and one for error. But why would you use the catch method if there's already an error callback? And what is its purpose? Here's an ...

Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object ...

Restore checkbox to default setting

Is it possible to reset checkboxes in a form back to their initial status using javascript, PHP, jQuery, or any other method? Here is the code I am currently using: <form method="POST> <input type="text" name="name" id="name" value="default val ...

Encountered an error while iterating through an array in Angular: "Cannot access property at index

I've encountered an error while trying to loop through an array of items and pushing them to another array. I am able to access the items at index "0", but still facing the mentioned error. Below is the code snippet for reference: createReportFormu ...

What's the best way to showcase certain data from a JSON object in a structured table format?

{"symbol":"DRREDDY","series":"EQ","openPrice":"3,132.00","highPrice":"3,229.90","lowPrice":"3,132.00","ltp":"3,206.35","previousPrice":"3,153.25","netPrice":"1.68","tradedQuantity":"74,165","turnoverInLakhs":"2,379.33","lastCorpAnnouncementDate":"18-Jul-20 ...

Leverage the power of AngularJS in ASP.NET without incorporating MVC

Is it possible to integrate AngularJS code into an ASP.NET project without using MVC architecture? I typically insert a script after the closing body tag like this: <script src="js/angular.js"></script> I have attempted to define the module ...

Tips for Customizing Dialogs with CSS Classes in mui5 Using Emotion/Styled

When attempting to customize the styling of a mui Dialog, I encountered an issue where it wouldn't accept className even when placed inside PaperProps. While inline styles worked, my preference was to import styles from a separate stylesheet named Sty ...

Is it a CSS or Javascript quirk when a div can become the child of the div before it?

On every browser I've checked, the code in the html is exactly the same: <td class="bardisplay"> <div class="bar hot" /> <div class="bar cool" /> </td> However, in the debugger of each browser, including Chrome, the DOM ...

Experiencing an "ENOTFOUND" error after attempting to make a large volume of API calls, possibly in the range of 100,000, to maps.google

I have a requirement to send a large number of requests to https://maps.googleapis.com/maps/api/place/queryautocomplete/json. Currently, I am fetching lists of strings from multiple files and sending requests to the mentioned API. When I test with 100 str ...

Top technique for extracting the value of a button using JavaScript

I am looking to extract the value of the value attribute from the button element and input it into a different modal. Within my PHP loop, I generate the following HTML: <button data-toggle="modal" data-target="#mod-error" type="button" class="myclasse ...

What could be the reason for the defaultCommandTimeout not functioning as expected in my script

Is there a way to wait for only one particular element in Cypress without having to add wait commands everywhere in the test framework? I've come across the solution of adding defaultCommandTimeout in the cypress.json file, but I don't want it t ...

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

Is it possible to anticipate a particular word following a route parameter in Node.js?

My current route setup looks like this: router.get('/:board/:threadId', function(req, res, next) { // performing actions here }); When users visit /a/1, it triggers the route with board = a and threadId = 1. Now, I want users to have to vis ...

Ending the connection in SignalR upon $destroy

I am currently working on a page that is utilizing SignalR, Angular, and Typescript. Upon the destruction of the current $scope (such as during a page change), I make an attempt to disconnect the client from the SignalR server: Controller.ts $scope.$on(&q ...

`The never-ending meteor cycle`

My goal is to modify the attributes of a Collection so that they have absolute positions before being rendered. I want the first item in the collection to have a top value of 0 and a left value of 0, the second item with a top of 0 and a left of 20, and so ...