在 MyController 中访问 rootScope 变量的语法

Syntax to access rootScope variable in MyController

在下面的代码中,

<!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>

使用 run 语法,在模块 (sample) 级别引入 $rootScope.variable

MyController?

中访问$rootScope.variable的语法是什么

像这样在控制器中注入 rootScope。

 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.

您可以执行以下操作,将 $rootScope 注入控制器

<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>