Reputation: 23
I am using $rootScope for passing value from one controller to another but i did not get the value in second controller(cart).
x.controller("first",function($scope,$http,$rootScope){
$scope.cart1=function(x,y){
$rootScope.img=x;
$rootScope.login=y;
}
});
x.controller("cart",function($scope,$rootScope){
$scope.cart2=$rootScope.img;
console.log($scope.cart2)
});
Upvotes: 0
Views: 4045
Reputation: 140
(function() {
"use strict";
angular
.module('app')
.factory("cartFactory", cartFactory);
function cartFactory($http) {
return {
login: '',
cart2:''
};
}})();
This is your factory you can use multiple controller like this...
var x =angular.module('app', [])
x.controller("first",function($scope,cartFactory){
cartFactory.login=x;
cartFactory.cartFactory=y;
}
});
x.controller("cart",function($scope,cartFactory){
$scope.login = cartFactory.login;
$scope.cart2 = cartFactory.cart2;
});
This is very simple to pass data one controller to another multiple controller.
Upvotes: 0
Reputation: 4175
why not using $broadcast
, considering your controller structure $scope.$parent
is enough, in oter case inject $rootScope
from where you are firing the $broadcast
var x =angular.module('app', [])
x.controller("first",function($scope){
$scope.cart1=function(x,y){
$scope.$parent.$broadcast('value changed', {x: X, y: y});
}
});
x.controller("cart",function($scope){
$scope.$on('value changed', function(data){
$scope.login = x;
$scope.cart2 = y;
});
});
Now your values are set in scope, use it whenever needed (in case of binding it will automatically reflect in UI)
Upvotes: 1
Reputation: 222522
$rootScope
does not get the value assigned if you simply define in controller, you need to transfer the data from controller1 to controller2 based on some event
DEMO
var x =angular.module('app', [])
x.controller("first",function($scope,$rootScope){
$scope.cart1=function(x,y){
console.log(x);
$rootScope.img=x;
$rootScope.login=y;
}
});
x.controller("cart",function($scope,$rootScope){
$scope.getData=function(){
$scope.cart2=$rootScope.img;
console.log($scope.cart2)
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="[email protected]" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body >
<div ng-controller="first">
<button ng-click="cart1('test','test2')">transfer</button>
</div>
<div ng-controller="cart">
<button ng-click="getData()">getStoredValue</button>
{{cart2}}
</div>
</body>
</html>
NOTE
Using $rootScope is not a recommended way to transfer variable across controllers, instead try using services
.
Upvotes: 1