gopal rao
gopal rao

Reputation: 293

AngularJS - Alternative to $scope in a factory

I understand that we cannot pass $scope in a factory in AngularJS like the one given below.

angular.module("MYAPP", [])
.factory("SLNservice", function($scope) { ...

Am i right?

If that is the case, in the below example -

angular.module("MYAPP", [])
.factory("SLNservice", function() {
return {
    edit: function a(x) {
     x.num = x.num + 1;
     return x.num;
 }
}
});

//controller code

 angular.module("MYAPP", [])
.controller("t", function($scope, SLNservice) {
$scope.num = 3; 
SLNservice.edit($scope.num);
console.log($scope.num);
});

Would the console.log above return 4? or in other words, since $scope cannot be accessed in a factory, can we pass the scope(variable/functions) like above and get the job done? Or should we wrap $scope in another object all together and pass it?

Or is there a better alternative? Suggestions welcome!

Upvotes: 0

Views: 790

Answers (2)

Chandermani
Chandermani

Reputation: 42669

You are confusing things. Remember AngularJS is plain javascript. All javascript rules hold good in Angular too.

If you have a reference to a $scope object you can pass it anywhere. $scope is just a normal javascript object.

What is not allowed is injecting $scope into a factory\service.

In the example above you can very well pass scope object to the function by calling edit($scope) in the controller. Nothing stops you from doing this. The risk involve in this case is that you may hold on the the $scope object in your factory at a global level and singe services are singleton, the scope may never get released, leading to memory leaks. Therefore you should avoid passing $scope to the service function. Instead pass sub properties to the function, such as edit($scope.user).

Also as highlighted earlier you cannot inject $scope. This is not allowed and does not make sense.

.factory("SLNservice", function($scope) {

Upvotes: 0

devang
devang

Reputation: 61

$scope cannot be accessed in a factory. we can pass the scope variables/functions to factory.

Factory is just like, service that, you can pass object/variable/function and you can get object/variable.

Regards, Devang

Upvotes: 2

Related Questions