Sadique
Sadique

Reputation: 139

Passing data from one view to another in angular

I am trying to load a view with custom message in it. So here is the scenario

Let say I am on index and I am going to navigate to index2.html.

Index2.html will render the custom message passed to it. One way is definitely to do it with $routeParams but I don't what to pass the information through the url, rather I want it in a general POST format where passed data is not exposed in url

Also I don't want to use localstorage, session or cookie. I want it in a way where I pass the data to the view and it should get rendered.

If anyone can help me with this

Upvotes: 0

Views: 898

Answers (1)

Dvir
Dvir

Reputation: 3339

FACTORY - The right way to share data between pages is a factory/service.

In this example I'll show you how to share data between two controllers, But it's the same thing. Once you invoke the service you have access to his instance and his data.

var myApp = angular.module('myApp', []);
 
myApp.factory('shareService', function(){
    return {
        title: "some title"
    };
});

myApp.controller('controller1', function($scope, shareService){    
    var ctrl1 = this;
    ctrl1.title = shareService.title;
});

myApp.controller('controller2', function($scope, shareService){
    var ctrl2 = this;
    ctrl2.title = shareService.title;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="controller1 as ctrl1">
        {{ctrl1.title}}        
    </div>
    <div ng-controller="controller2 as ctrl2">
        {{ctrl2.title}}
    </div>    
</div>
    

Read more about services on AngularJs doc



UPDATE

A working example for routing and shared data on plunkr

Upvotes: 4

Related Questions