Search code examples
javascriptangularjssingle-page-applicationngroute

Angularjs Updated table after clicking a link with parameters


I am making an Single Page Application

My config:

var app = angular.module('menuCardMaker', ['ngRoute']);

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider
    .when('/wines', {
        templateUrl: 'templates/wine/wine.html',
        controller: 'WineController'
    })
    .when('/wines/delete/:id', {
        templateUrl: 'templates/wine/wine.html',
        controller: 'WineController'
    })

My HTML:

     <table>
        <tr>
            <td class="head">Name</td>
        </tr>
        <tr ng-repeat="wine in winesFromStorage">
            <td>{{ wine.name }}</td>
            <td><a ng-href="#/wines/delete/{{ wine.id }}" ng-click="remove()">Delete</a></td>
        </tr>
    </table>

Page loads on URL (for example) on http://127.0.0.1:8080/#/wines/delete/1 when the user clicks on delete. It deletes the record in my LocalStorage, but it does not 'refresh' my page like I would expect from my templateUrl in my config.

The user has to reload the page before the table shows the correct data. Any thoughts that could guide me to a solution?


Solution

  • Do you want to remove the wine and redirect the user to another page or do you just want to remove the wine?

    .controller('WineController', ['$scope', '$location' function ($scope, location) {
         $scope.wines = ['wine1', 'wine2]; 
    
         $scope.deleteWine = function(wineIndex){
             // this should update the ng repeat list on your page
             delete $scope.wines[wineIndex];
             // if you still want to redirect the user you could do 
             // it like this:
             $location.path('/yoururlhere'); 
             // of course this would load another route with another controller. 
             //If you want to share the current wine list between two 
             //controllers, you could create a wineListService where 
             //you store the list. 
         }
    
    };
    

    an example how to share data between controllers can be found here: Share data between AngularJS controllers