0

I have project which is a single page application.So that I am using angular js route. In the first controller I have a $scope value.The same value i have to use in the other controller

here is my controller.js file

var module = angular.module("sampleApp", ['ngRoute']);

    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/route1', {
                    templateUrl: 'http://localhost/MyfirstApp/welcome',
                    controller: 'RouteController1'
                }).
                when('/route2', {
                    templateUrl: 'http://localhost/MyfirstApp/result',
                    controller: 'RouteController2'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }]);

    module.controller("RouteController1", function($scope) 
    {
       $scope.value="Athira" 


    })
    module.controller("RouteController2", function($scope) {
     $scope.text=$scope.value + "Sandeep" 
    })

In the result page it should show as 'Athira Sandeep'

thank you for any kind of help

user1187
  • 2,116
  • 8
  • 41
  • 74
  • 4
    Possible duplicate of [AngularJS: How can I pass variables between controllers?](http://stackoverflow.com/questions/12008908/angularjs-how-can-i-pass-variables-between-controllers) – Pirate X May 09 '16 at 10:38
  • that is using services they have explained. I want this using router – user1187 May 09 '16 at 10:40
  • @athi not sure what you mean by saying "i want this using router" – Yatin Gera May 09 '16 at 10:43
  • In '$routeProvider' Can i use services or factory?. I am new in angularjs. – user1187 May 09 '16 at 10:44
  • If we pass the controller in route provider can I get the controller scope value – user1187 May 09 '16 at 10:45
  • @Athi you just need to refer the factory/service in the controller. It doesn't depend if you are using routing or not. The basic working of controller would remain the same. Just define a dependency on the service in the controller when you register them and use them – Yatin Gera May 09 '16 at 10:52
  • ok thank you.first I need to learn factory/service :-) – user1187 May 09 '16 at 10:58

1 Answers1

0

Use a service to share data among controllers . Another option could be event emitters which i personally am not a fan because it populates the rootScope (in this case) with a lot of events.

What you could do it

angular.module('app',[])
.factory('SharedScope',function(){
var fac = this;
var scope = "";
var sharedScope = {
getScope : function(){
return fac.scope;
},
setScope: function(scope){
fac.scope = scope
}
};
return sharedScope;
})
.controller('Ctrl1',function('SharedScope'){
SharedScope.setScope("Angular");
})
.controller('Ctrl2',function('SharedScope'){
var data = SharedScope.getScope();
$scope.text = data + " is awesome"; //would get Angular is awesome
});

Hope this helps.

Yatin Gera
  • 191
  • 1
  • 7