Reputation: 200
I have two controllers like below. I want to use first controller methods/variables in other controller
app.controller("createController", ["$scope",
function ($scope)
{
$scope.i = 0;
$scope.changeEstimateStatus = function()
{
console.log('changeEstimateStatus');
};
}]);
app.controller("editController", ["$scope",
function ($scope)
{
//here how can I access 'i' variable of createController
}]);
Upvotes: 0
Views: 88
Reputation: 3536
You should move the common functionality (changeEstimateStatus) into a service. Rather than one controller depending on the other, both controllers depend on the service.
app.service('estimateService', function() {
this.changeEstimateStatus = function() {
console.log('changeEstimateStatus');
};
});
app.controller("createController", ["$scope","estimateService",
function ($scope, estimateService)
{
$scope.i = 0;
$scope.changeEstimateStatus = function()
{
estimateService.changeEstimateStatus(); //delegate to the service
};
}]);
app.controller("editController", ["$scope", "estimateService"
function ($scope, estimateService)
{
$scope.changeEstimateStatus = function()
{
estimateService.changeEstimateStatus(); //delegate to the service
};
}]);
Another option is to use $rootScope, but using services is not as brittle to change.
Upvotes: 0
Reputation: 104775
Use a shared service:
app.service("mySharedService", [function() {
var _x = null;
return {
setX: function(val) { _x = val },
getX: function() { return _x }
}
}]);
Then inject into your controller:
app.controller("createController", ["$scope","mySharedService", function($scope, mySharedService) {
$scope.i = mySharedService.getX(); //get
mySharedService.setX(3); //set
}]);
Upvotes: 3
Reputation: 23211
use one of this:
1.you can use serveice and put common function to that service and access that function to all controlller.
app.service('MyService', function() {
this.changeEstimateStatus = function()
{
console.log('changeEstimateStatus');
};
});
app.controller("createController", ["$scope",MyService,
function ($scope,MyService)
{
$scope.i = 0;
MyService.changeEstimateStatus ();
}]);
app.controller("editController", ["$scope", app.controller("createController", ["$scope",$rootScope,
function ($scope,$rootScope)
{
$scope.i = 0;
MyService.changeEstimateStatus ();
}]);
2.you can store that function in $rootscope object.and then access that function to all controlller.
like:
app.controller("createController", ["$scope",$rootScope,
function ($scope,$rootScope)
{
$scope.i = 0;
}]);
app.controller("editController", ["$scope",$rootScope,
function ($scope,$rootScope)
{
$rootScope.changeEstimateStatus ();
}]);
but 2nd option is not a good aproach.
Upvotes: 0