Search code examples
angularjsangular-ui-routerangular-servicesng-view

Passing data from one route view to another


I want to pass some values from one view to another in Angularjs using ui-Router.
I don't want to use $rootScope to save data or create a new services ( as I have many views that pass small bits of data so creating new jsfile for few lines code is not fun). A super-minified example of what I want to do is:

Controller of View 1
$scope.goodFood = 10 $scope.badFood = 2

Controller of View 2
$scope.results = 10 - 2 (from view 1's scope)

Is there any quick way to do these kinds of small operations ?


Solution

  • I don't want to use $rootScope to save data or create a new services ( as I have many views that pass small bits of data so creating new jsfile for few lines code is not fun)

    There is no need to create a new service for new bits of data. Simply create a value service with an object:

    app.value("viewData", {});
    

    Then simply add new properties as needed:

    app.controller("viewCtrl", function(viewData) {
        viewData.newProp = "new info";
        console.log(viewData.oldProp);
    });
    

    As value services are singletons, changes to the contents of the object will survive view changes.