angular学习笔记2-$rootScope、run方法、angular代码压缩

1, $rootScope为全局变量,可以在根app内任意使用

<div ng-controller="firstController">
        {{name}}
        <div ng-controller="secondController">
            {{age}}

        </div>
    </div>
var myapp = angular.module("myApp", []);

    myapp.controller("firstController", function ($scope) {
        $scope.name = "李四";
    });

    //    $rootScope为全局变量,可以在根app内任意使用
    myapp.controller("secondController", function ($rootScope) {
        $rootScope.age = "25";
    });

 

2,angular代码压缩写法,对于引号内的字符串不进行压缩
 

<div ng-controller="tar">
        <div ng-bind="country"></div>
        <div ng-bind="hometown"></div>}
</div>
//    angular代码压缩写法,对于引号内的字符串不进行压缩
    myapp.controller("tar", ["$scope", "$rootScope", function ($s, $r) {
                $s.country = "中国";
                $r.hometown = "故乡";
            }]
    );

 

3,全局变量$rootScope还可以使用run方法
<div ng-controller="tar">
        <div ng-bind="country"></div>
        <div ng-bind="hometown"></div>

        <!--使用全局变量run的一个例子-->
        {{sex}}
    </div>
myapp.run(["$rootScope", function ($rootScope) {
        $rootScope.sex = "楠";
    }]);

 

以下为代码示例:
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 5     <title>无标题文档</title>
 6     <script type="text/javascript" src="../angular/angular.min.js"></script>
 7 </head>
 8 <body>
 9 <div ng-app="myApp">
10     <div ng-controller="firstController">
11         {{name}}
12         <div ng-controller="secondController">
13             {{age}}
14 
15         </div>
16     </div>
17 
18     <div ng-controller="tar">
19         <div ng-bind="country"></div>
20         <div ng-bind="hometown"></div>
21 
22         <!--使用全局变量run的一个例子-->
23         {{sex}}
24     </div>
25 </div>
26 <script>
27     var myapp = angular.module("myApp", []);
28 
29     myapp.controller("firstController", function ($scope) {
30         $scope.name = "李四";
31     });
32 
33     //    $rootScope为全局变量,可以在根app内任意使用
34     myapp.controller("secondController", function ($rootScope) {
35         $rootScope.age = "25";
36     });
37 
38     //    angular代码压缩写法,对于引号内的字符串不进行压缩
39     myapp.controller("tar", ["$scope", "$rootScope", function ($s, $r) {
40                 $s.country = "中国";
41                 $r.hometown = "故乡";
42             }]
43     );
44 
45     //    全局变量$rootScope还可以使用run方法
46     myapp.run(["$rootScope", function ($rootScope) {
47         $rootScope.sex = "";
48     }]);
49 
50 
51 </script>
52 </body>
53 </html>

 

 
 

posted on 2016-08-18 11:48  ziyi_ang  阅读(193)  评论(0编辑  收藏  举报

导航