user3406754
user3406754

Reputation: 69

Angularjs state retension

I am adding row dynamically using angularjs. But the problem is that I want to retain this state all over the application. For example in view-1 I add one dynamic row to the table and move to view-2 after coming from view-2 the added row should be available. So is there any method to retain the state of view in angularjs. Following is the code I used to add row dynamically:

angular.module('MyApp', [])
.controller('MainController', [ '$scope', function($scope) {

  $scope.rows = ['Row 1'];

  $scope.counter = 2;

  $scope.addRow = function() {

    $scope.rows.push('Row ' + $scope.counter);
    $scope.counter++;
  }
}]);


<body ng-controller="MainController">

    <a href="#" class="button" ng-click="addRow()">Add Row {{counter}}</a>

    <table>
        <thead>
            <tr>
                <th width="200">Some Header</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="rowContent in rows">
                <td>{{rowContent}}</td>
            </tr>
        </tbody>
    </table>    

</body>

Thanks.

Upvotes: 0

Views: 197

Answers (1)

Yes. You should save the model used to build the table (with the new rows aswell) to a Service. Then you inject that service in your controllers.

To be able to see a little bit of your code would be nice, though. But here goes an example of how to do this:

DISCLAIMER

Untested example

    angular.module('yourapp').factory('MySharedService',function(){

       var myTableModel = [];

       function addRow(row){
         myTableModel.push(row);
         return myTableModel;
       }

       return  {
           addRow: addRow,
           tableModel: myTableModel
       }

    })
    .controller('MyFirstController',['$scope','MySharedService',function($scope,
                MySharedService){

         $scope.tableModel = MySharedService.tableModel;

         $scope.addRow = function(row){
            $scope.tableModel = MySharedService.addRow(row);
         }

    }]).controller('MySecondController',['$scope','MySharedService',function($scope,
                  MySharedService){...}]);

EDIT: After researching a bit further on this, I've found a similar question with a couple ways of achieving this and with sample code here Check it out and see if it helps you.

Upvotes: 1

Related Questions