0

在下面的代码中,

<!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语法,$rootScope.variable在模块(sample)级别介绍。

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

4

2 回答 2

2

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

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

 };

除了您的问题,我不知道您为什么在视图中混合控制器代码。Angular 是基于 MVVM 模式构建的。因此建议将控制器和视图分开。

于 2016-03-21T16:57:13.477 回答
0

您可以执行以下操作,将 $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>
于 2016-03-21T16:59:20.983 回答