ghiscoding
ghiscoding

Reputation: 13194

From AngularJS how to pass data from a controller+template to another controller+template?

I'm building an application with AngularJS and Slim PHP framework for the backend, now I completed my 1st form and created a route to the template for it. Now my problem arise when I want to pass my data to another controller, I need to pass the data to another controller+view(template), I don't want to pollute my first view neither the controller of it and so I really want/need to pass the data to another controller which I could play with my data and another form (the 2nd form is for calculation and other stuff)...So you can call the first controller a pre-save, while the real data save (backend to DB) will only happen in the second controller+template. Here is a short of my 1st template view that has the form:

<form novalidate id="formAdd" name="formAdd" class="form-horizontal well col-md-7 col-md-pull-5" method="post">
    <fieldset>
        <legend>Transaction form</legend>

        <div class="form-group">
            <label for="symbol" class="col-sm-4 control-label">Symbol</label>
            <div class="col-sm-5 symbols">
                <input type="text" name="symbol" class="form-control" ng-model="trsn.symbol" placeholder="symbol" required />
          </div>  
        </div>                    
        <div class="form-group">
            <label for="accnt_id" class="col-sm-4 control-label">Account</label>
            <div class="col-sm-5">
                <select id="accnt_id" name="accnt_id" ng-model="trsn.accnt_id" class="form-control" required>
                    <option value="">...</option>   
                    <option ng-repeat="account in trsn.accounts" value="{{account.accnt_id}}">{{account.accnt_name}}</option>
                </select>
            </div>
        </div> 
        <!-- ....etc, etc.... -->

        <div class="form-actions col-sm-8 col-sm-offset-4">
            <button type="submit" name="save_btn" class="btn btn-primary" ng-disabled="formAdd.$invalid" ng-click="preSaveTrsn(trsn, formAdd)">Save transaction</button>
            <button type="reset" class="btn btn-default">Cancel</button>
        </div>          
    </fieldset>
</form>

then the app with the module and routes:

var investingApp = angular.module('investingApp', ['ngSanitize','ngResource', 'ngRoute'])
    .config(function($routeProvider, $locationProvider) {
        $routeProvider.when('/new-trsn',
            {
                templateUrl: 'templates/StockTransaction.html',
                controller: 'StockTransactionController'
            });
        $routeProvider.when('/presave-trsn',
            {
                templateUrl: 'templates/PreSaveTransaction.html',
                controller: 'PreSaveTrsnController'
            });        
    });

now inside my first controller is the presave function, which is empty since I don't know what to do with it so that I can send the transaction data to the next controller+view:

investingApp.controller('StockTransactionController', 
    function TransactionController($scope, $http, $location, $compile, $timeout, transactionDataService, dateFilter) {
        // define some default variables
        $scope.trsn = {};
        $scope.trsn.symbol = "";
        ...
        $scope.preSaveTrsn = function(trsn, formAdd) {          
            // what to put in here to transfer data to next controller????
        };

and then my last controller, I have also nothing in there yet since I can't receive any data....but basically what I want to inject is the transaction data (trsn) which comes from 1st form/controller.

investingApp.controller('PreSaveTrsnController', 
    function MenuController($scope, $http, trsn) {
        console.debug(trsn);
});

Does I have to put something inside the routeProvider somehow? ...or does I have to fill in something special inside the preSaveTrsn function inside my 1st controller??? I'm quite confused with this since all example I find are for saving right away to database, but I can't do that the way I build my app, it really has to be on the second controller for few reasons which I don't think I have to explain here.... Thanks for any help given :)

Upvotes: 0

Views: 1993

Answers (2)

user2445933
user2445933

Reputation:

You may create a lightweight service - value

angular.module('investingApp').value('MySharedValue', {});

And then inject it in both controllers:

TransactionController($scope, $http, $location, $compile, $timeout, transactionDataService, dateFilter, MySharedValue)

And just to assign your shared value to it

        $scope.preSaveTrsn = function(trsn, formAdd) {          
            MySharedValue.trsn = trsn;
        };

Upvotes: 5

Chandermani
Chandermani

Reputation: 42669

There are 2 ways to achieve it. First is to declare your model object on $rootScope or on a scope which is parent to both of these controller scope. This way the data gets shared and the changes are available to both controller, irrespective of who makes it.

The second better approach is to create a service which tracks the model update. Inject this service into both the controller. Any controller can ask ask for the model from the service and update it. Since services are singleton, the model changes are shared across controller.

Like

angular.module("myApp",[]).factory('transactionService',[function(){
   var service={};
   var model={};
   service.preSaveTrsn = function(trsn, formAdd) {          
        //set model here
    };
   service.getPreSaveTrsn=function() {
       return model;
   }
   return service;
}]);

Upvotes: 1

Related Questions