Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to inject the $rootScope into Controller in order use or override models/method defined under $rootScope in AngularJS?

Tags:

angularjs

I've defined some models in App.run below which I'm overriding within the controller someCtrl:

App.run(['$rootScope', function($rootScope) {
  $rootScope.attempt = 1;
});

function someCtrl($scope, $rootScope) {
  $rootScope.attempt = 2;

  $rootScope.checkAttempt = function () {
    return $rootScope.attempt > 1 ? true : false;    
  };
}

There is a button on the page out of someCtrl's scope:

<button class='btn' ng-disabled="checkAttempt()">Who's changing my value?</button>

FYI, I'm aware of creating a service or using emit-broadcaste mechanism to share data across controllers but I would like to know How authenticate is it to inject $rootScope into a controller?

like image 372
codef0rmer Avatar asked Oct 13 '12 17:10

codef0rmer


People also ask

What is $rootScope and how do we use it?

Root Scope All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.

How many $rootScope in Angular application can have?

An app can have only one $rootScope which will be shared among all the components of an app.

Which of the following is true about ng-controller directive?

Q 18 - Which of the following is true about ng-controller directive? A - ng-controller directive tells AngularJS what controller to use with this view. B - AngularJS application mainly relies on controllers to control the flow of data in the application.

Which is the correct syntax of creating AngularJS controller?

The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller. The myCtrl function is a JavaScript function. AngularJS will invoke the controller with a $scope object.


1 Answers

IMHO, I think its fine to inject $rootScope into a controller. I would recommend using emit/broadcast.

like image 137
Dan Doyon Avatar answered Nov 15 '22 12:11

Dan Doyon