Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting $scope object in Angular's run() method

Tags:

angularjs

I'd like to do some stuff when my app loads to set up the default state. So I'm trying to use the run method on the Module object. When I try to access the $scope variable though I get an "Uncaught ReferenceError: $scope is not defined" message in my console.

See the following example http://jsfiddle.net/F2Z2X/1/

app = angular.module('myapp', []);  app.controller('mycontroller', function($scope){     $scope.data = { myvariable: 'Hello' }; });  app.run(     alert($scope.data.myvariable)) ); 

Am I going about this all wrong?

For example, I want to run the watchAction function once at the beginning, to hide UI elements that aren't called for yet, but the watchAction function doesn't have the $scope object because it's not being called by the watch method so I have to pass it to it, but alas it's not available.

like image 845
Tristan Avatar asked Jun 28 '13 18:06

Tristan


People also ask

How do you get the $scope in console?

scope(); $('#elementId'). scope(). $apply(); Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0 .

Is $scope still supported in angular2?

In Angular 2.0, there will be no $scope .

What does $scope mean in AngularJS?

The $scope in an AngularJS is a built-in object, which contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it. The $scope is glue between a controller and view (HTML).

What is $scope angular 8?

AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.


1 Answers

app.run(function ($rootScope) {     $rootScope.someData = {message: "hello"}; }); 

You can only get $rootScope injected to services and run function, because each child scope is inherited from its parent scope and the top level scope is rootScope. Since it would be ambigous to inject any scope. Only root scope is provided.

like image 167
Umur Kontacı Avatar answered Oct 06 '22 22:10

Umur Kontacı