user4648142 user4648142 - 2 months ago 13
AngularJS Question

How to pass data from one view to another with Angular

I need to pass data between views. I have a view where you check items and then another view where those items you can check get put. The problem is you lose all data when you redirect to another page so I lose all the data on the checked items.

Possible solutions?:

Calls to DB to save all the items and then just deleting when done (Seems improper and wasteful use of server)

Someone told me to you can actually POST to a page and then redirect

Saving the Data in an Angular Service (I tried this by just saving a number in a variable but it didn't seem like it worked. Saw this on another SO post)

EDIT:
I just saw something about a AngularJS factory but it doesn't seem like it work with dynamic data and It seems like I tried that with the service thing and it didn't work.

Also here is the code for the service testing. Theres also just the controller methods calling the GetTest and test methods.

MutualService

var test = function (data) {
test1 = data;
console.log(data);
};

Test: function (data) {
return test(data);
},
GetTest: function () {
return test1;
}


View1

<button style="float: right; margin-bottom:20px;" class="btn btn-sm btn-primary" onclick="changeLocation()"> Change Location</button>
<button style="float: right; margin-bottom:20px;" class="btn btn-sm btn-primary" ng-click="vm.Test(2)"> Purchase Order</button>


<script>
changeLocation = function () {
window.location.href = '/Purchasing/Manage/CreateEditPurchaseOrder';
}
</script>

Answer

So what you can do here is create an AngularJS Service with the value to share. Inject the Service into either a controller or directive for each view. Then by assigning the service variable to both Scopes you can have the same variable in both places.

angular.module('myModule')
    .service('Test', [ 
       function () {
            var test = this;

            test.myValue = 'default';

            return test;
       }
    ]
);

angular.module('myModule')
    .directive('viewOne', [ 'Test' 
       function ( Test ) {
            return {
                 restrict: 'E',
                 templateUrl: 'my/path/to/viewOne',
                 scope: {},
                 link: function ( $scope ) {
                      $scope.myValue = Test.someValue;
                 }
            };
       }
    ]
);

angular.module('myModule')
        .directive('viewTwo', [ 'Test' 
           function ( Test ) {
                return {
                     restrict: 'E',
                     templateUrl: 'my/path/to/viewTwo',
                     scope: {},
                     link: function ( $scope ) {
                          $scope.myValue = Test.someValue;
                     }
                };
           }
        ]
    );
Comments