Ali Nafees
Ali Nafees

Reputation: 195

What is the disadvantage of using the $scope as variable in angularjs, to share $scope of a controller inside the app.run?

What is the disadvantage of using the $scope as variable in AngularJS, to share $scope of a controller inside the app.run()? Actually I am doing that to make code generic to be called from all the controllers with same function in app.run().

The function I am using is with the

$rootScope.getUserInfo = function($scope){
  $scope.userinfo = '---------';
}

where $scope is the variable that I am passing from every controller like that

$rootScope.getUserInfo($scope);

Upvotes: 0

Views: 592

Answers (2)

Chetas Mehta
Chetas Mehta

Reputation: 1

Instead of using $scope, you can use var vm = this; and define everything in that controller with vm.variablename_or_funcname instead of $scope.variablename_or_funcname

And you can attach that controller in html like ng-controller = "mycontroller as vm"

More info: https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/

Upvotes: 0

Steve Klösters
Steve Klösters

Reputation: 9457

I don't think there's inherently something wrong with passing around a scope. People do this a lot in AngularJS services and it's internally done a lot, too: your created controller is passed a scope to work with.

However, I would say it's not necessary in your example to have getUserInfo to depend on a scope being passed. Why not return the user information and have the caller put it on the scope? That way, you can use it in parts of your app that don't have a scope.

Upvotes: 1

Related Questions