Reputation: 2299
I've a login service which gives me JSON object as a response having user details. Now in this response, there's an object named permissions which gives me information about the CRUD permission allowed to the user.
It looks like this :
Now I've different pages, each page having a table. What I want is to check the permission of the logged in user and according to that show/hide the element to create/read/update/delete the record from the table.
What I am currently doing is saving the object onto an array :
$scope.permissionArry = [];
for (var i = 0; i < data.permissions.length; i++) {
$scope.permissionArry.push({
moduleId: data.permissions[i].module_id,
createModule: data.permissions[i].create_module,
readModule: data.permissions[i].read_module,
updateModule: data.permissions[i].update_module,
deleteModule: data.permissions[i].delete_module
});
}
and then trying to pass this array to other controller.
As we know we cannot pass $scope in service/factory I don't know how to proceed (I don't want to use $rootScope).
Upvotes: 0
Views: 2348
Reputation: 1702
I got around a same problem. I used the solution which will not be likable or I would say there must be a better approach using angular service or factory to do that (I don't know about those).
The solution I worked with is using sessionStorage or localStorage of HTML5. I know its not the angular way of doing things but it will get the job done.
In Controller 1
sessionStorage.setItem('permissions', JSON.stringify($scope.permissionArry));
And to get the item in controller 2,
$scope.permissions = JSON.parse(sessionStorage.getItem('permissions'));
I personally think that there must exist better solutions than this and you should think about learning angular factory or service to solve the problem. But meanwhile you can use this solution for a quick way around
Upvotes: 0
Reputation: 647
This is an issue about learning how to pass data between two controllers via a factory or service. You don't need to pass the $scope variable because you should be binding the data to an object in the factory.
Here is a simple example:
Controller 1
myApp.controller('Ctrl1', ['$scope', 'myFactory', function($scope, myFactory){
myFactory.data = someFunctionThatChangesTheData();
}]);
Controller 2
myApp.controller('Ctrl2', ['$scope', 'myFactory', function($scope, myFactory){
$scope.data = myFactory.data;
}]);
and finally your Factory
myApp.factory('myFactory', function(){
return {
data: {
value: 'some data'
}
}
});
You could then use the data from Controller two in a view:
View 2 (Assigned Ctrl2)
<div>
<h1>View 2</h1>
<p>{{data.value}}</p>
</div>
Upvotes: 1
Reputation: 8934
It very simple you need to use service to achieve this:
example can be found link
MyApp.app.service("xxxSvc", function () {
var _xxx = {};
return {
getXxx: function () {
return _xxx;
},
setXxx: function (value) {
_xxx = value;
}
};
});
Upvotes: 1