0

In the below code,

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.20/angular.js"></script> <script type="text/javascript"> function MyController() { this.Name = "jag"; this.sal = "4500"; } MyController.prototype.getAnnualSal = function(){ return (this.sal) * 12; } var app = angular.module("sample", []).run(function($rootScope) { $rootScope.variable = 1; }); app.controller("emp", MyController); </script> </head> <body ng-app="sample"> <div ng-controller="emp as o" > Hello {{o.Name}}, your annual salary is {{o.getAnnualSal()}} </div> </body> </html> 

Using run syntax, $rootScope.variable is introduced at module(sample) level.

What is the syntax to access $rootScope.variable in MyController?

2 Answers 2

2

Inject rootScope in controller like this.

 angular.module('sample', []).controller('emp', function($scope, $rootScope) { }; 

Aside from your issue I dont know why you are mixing controller code in view.Angular is built on MVVM pattern.So separation of controller and view is recommended.

Sign up to request clarification or add additional context in comments.

3 Comments

One supple: In my code, What is the advantage of creating Name and sal as member of controller instance(o) rather than members of $scope? FYI.. I know that controller instance is a member of $scope. One reference-codetunnel.io/angularjs-controller-as-or-scope
So, Cant't we take similar approach, without injecting $rootScope in controller? Otherwise, I did know the syntax that you wrote in the answer
@overexchange :what are you doing with rootScope? $rootScope shouldn't be used to share variables when we have things like services and factories.However you can use .scope().$root also to indirectly get hold of rootscope;
0

You could do the following, inject $rootScope into the controller

<script type="text/javascript"> function MyController($rootScope) { this.Name = "jag"; this.sal = "4500"; } MyController.prototype.getAnnualSal = function(){ return (this.sal) * 12; } var app = angular.module("sample", []).run(function($rootScope) { $rootScope.variable = 1; }); MyController.$inject = ['$rootScope']; app.controller("emp", MyController); </script> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.