AngularJS常用Directives实例

 在第一篇 认识AngularJS 中,我们已经基本了解了AngularJS,对Directive也有了一定了解,本章我们将继续介绍Directive,对其有一个更深入的了解和掌握。

常用的Directives

 除了第一篇中已提到过的: ng-app, ng-controller, ng-show(与之对应的当然还有ng-hide)这几个内建的Directive之外,我们还将了解另外几个非常常用的Directive。

 1. ng-repeat (根据集合重复创建指定的模板):

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <script src="/Scripts/angular.js"></script>
 5     <script type="text/javascript">
 6         (function () {
 7             var app = angular.module('student', []);
 8             
 9             // 这次定义一个数组students,里面有三个学生Jack、Mary、Tom
10             var students = [{
11                                 name: "Jack",
12                                 age: 18,
13                                 sex: 'male',
14                                 displayComment: false
15                             },
16                             {
17                                 name: "Mary",
18                                 age: 16,
19                                 sex: 'female',
20                                 displayComment: true
21                             },
22                             {
23                                 name: "Tom",
24                                 age: 17,
25                                 sex: 'male',
26                                 displayComment: true
27                             }];
28 
29             app.controller('myController', function () {
30                 this.students = students;
31             });
32         })();
33     </script>
34 </head>
35 <body ng-app="student">
36     <div ng-controller="myController as myCtrl">
37         <!--使用ng-repeat,优雅的迭代显示所有学生信息-->
38         <div ng-repeat="stu in myCtrl.students">
39             <p>Student{{myCtrl.students.indexOf(stu) + 1}}:</p>
40             <p>Name:{{stu.name}}</p>
41             <p>Age:{{stu.age}} will be {{stu.age+15}} after 15 years.</p>
42             <p>Sex:{{stu.sex}}</p>
43             <p ng-show="stu.displayComment">Comments:This will not display on page.</p>
44             <br />
45         </div>
46     </div>
47 </body>
48 </html>

 

2. ng-model(ng-model定义一个变量,该变量在Scope范围内可被直接使用,关于Scope今后有机会可能需要单独写一章):

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <script src="/Scripts/angular.js"></script>
 5 </head>
 6 <body ng-app>
 7     <input ng-model="yourname" />
 8     <br />
 9     Your name is: {{yourname}}
10 </body>
11 </html>

 

3. ng-src & ng-href:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <script src="/Scripts/angular.js"></script>
 5     <script type="text/ecmascript">
 6         (function () {
 7             // 注意,这个demo中我们使用连缀的形式书写代码,这个和以前不一样
 8             // 个人认为连缀的形式没有单独书写清晰
 9             angular.module('src.href.test', [])
10                 .controller('myController', function () {
11                     this.imgName = "112348515178380.png";
12                 });
13         })();
14     </script>
15 </head>
16 <body ng-app="src.href.test">
17     <div ng-controller="myController as myCtrl">
18         <a href="//images0.cnblogs.com/blog2015/455688/201505/112348515178380.png">A link</a>
19         <br />
20         <img src="//images0.cnblogs.com/blog2015/455688/201505/112348515178380.png" />
21         <br />
22         myCtrl.imgName : {{myCtrl.imgName}}
23         <br />
24         <a href="//images0.cnblogs.com/blog2015/455688/201505/{{myCtrl.imgName}}">A link</a>
25         <br />
26         <img src="//images0.cnblogs.com/blog2015/455688/201505/{{myCtrl.imgName}}" />
27     </div>
28 </body>
29 </html>

特别注意:按照官方的说法,直接使用src或者href属性时,由于渲染页面时,AngularJS还没开始解析src或者href中的Expression,因此将会得到一个404错误(因为地址直接被解析成了//images0.cnblogs.com/blog2015/455688/201505/{{myCtrl.imgName}} )。实际上,若运行以上的代码,我们会惊喜的发现,并没有看到图片404错误。真的是这样吗?如果你用开发者工具看一下加载项,就能知道发生了什么。确实如官方文档所说,实际发生了一次404错误,但是AngularJS解析了Expression之后,图片又被加载了一次,因此从表面上我们并未察觉错误。所以结论是,最好使用ng-src/ng-href避免该问题的发生。

 

4. 事件类Directives,以ng-click为例(类似的还有ng-blur,ng-change,ng-checked,ng-dblclick,ng-keydown, ng-keypress, ng-keyup, ng-mousedown, ng-mouseenter, ng-mouseleave, ng-mouseup):

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <script src="/Scripts/angular.js"></script>
 5     <script type="text/javascript">
 6         (function () {
 7             var app = angular.module('clicktest', []);
 8 
 9             app.controller('myController', ['$scope', function ($scope) {
10                 this.sayHello = function () {
11                     alert("Hello, " + $scope.yourname);
12                 };
13             }]);
14 
15             // 以下代码与上面的功能一样,但是推荐上面这种写法,今后讲AngularJS的服务的时候将会讲到。
16             // 主要原因是js可以被压缩、加密等操作,$scope 将被变换从而AngularJS无法识别它, 但字符串 '$scope' 是不会被变换的
17             //app.controller('myController', function ($scope) {
18             //    this.sayHello = function () {
19             //        alert("Hello, " + $scope.yourname);
20             //    };
21             //});
22         })();
23     </script>
24 </head>
25 <body ng-app="clicktest">
26     <div ng-controller="myController as myCtrl">
27         <input ng-model="yourname" />
28         <br />
29         <button ng-click="myCtrl.sayHello()">Say Hello</button>
30     </div>
31 </body>
32 </html>

特别注意下被注释的那部分代码和注释部分的说明。

 

5. ng-class, ng-class-even, ng-class-odd:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <style type="text/css">
 5         .odd {
 6             color: red;
 7         }
 8 
 9         .even {
10             color: blue;
11         }
12 
13         .green_bold {
14             color: green;
15             font-weight: bold;
16         }
17     </style>
18 
19     <script src="/Scripts/angular.js"></script>
20     <script type="text/javascript">
21         (function () {
22             var app = angular.module('student', []);
23 
24             var students = [{
25                                 name: "Jack",
26                                 age: 18,
27                                 sex: 'male',
28                                 displayComment: false
29                             },
30                             {
31                                 name: "Mary",
32                                 age: 16,
33                                 sex: 'female',
34                                 displayComment: true
35                             },
36                             {
37                                 name: "Tom",
38                                 age: 17,
39                                 sex: 'male',
40                                 displayComment: true
41                             }];
42 
43             app.controller('myController', function () {
44                 this.students = students;
45             });
46         })();
47     </script>
48 </head>
49 <body ng-app="student">
50     <div ng-init="myVar='green_bold'">
51         <p ng-class="myVar">This should be green.</p>
52     </div>
53     <div ng-controller="myController as myCtrl">
54         <!--这里添加了 ng-class-odd 和ng-class-even 属性-->
55         <div ng-repeat="stu in myCtrl.students" ng-class-odd="'odd'" ng-class-even="'even'">
56             <p>Student{{myCtrl.students.indexOf(stu) + 1}}:</p>
57             <p>Name:{{stu.name}}</p>
58             <p>Age:{{stu.age}} will be {{stu.age+15}} after 15 years.</p>
59             <p>Sex:{{stu.sex}}</p>
60             <p ng-show="stu.displayComment">Comments:This will not display on page.</p>
61             <br />
62         </div>
63     </div>
64 </body>
65 </html>

 

6. ng-submit(偷懒直接引用了官方的demo):

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <script src="/Scripts/angular.js"></script>
 5     <script type="text/javascript">
 6         (function () {
 7             var app = angular.module('submitExample', []);
 8 
 9             app.controller('ExampleController', ['$scope', function ($scope) {
10                 $scope.list = [];
11                 $scope.text = 'hello';
12                 $scope.submit = function () {
13                     if ($scope.text) {
14                         $scope.list.push(this.text);
15                         $scope.text = '';
16                     }
17                 };
18             }]);
19         })();
20     </script>
21 </head>
22 <body ng-app="submitExample">
23     <form ng-submit="submit()" ng-controller="ExampleController">
24         Enter text and hit enter:
25   <input type="text" ng-model="text" name="text" />
26         <input type="submit" id="submit" value="Submit" />
27         <pre>list={{list}}</pre>
28     </form>
29 </body>
30 </html>

特别注意的是:ng-submit将默认阻止Submit的默认提交动作。

 

7. ng-include (将Html片段加载到指定位置):

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <script src="/Scripts/angular.js"></script>
 5     <script type="text/javascript">
 6         (function () {
 7             var app = angular.module('ngIncludeTest', []);
 8             app.controller('myController', ['$scope', function ($scope) {
 9                 $scope.info = {
10                     yourname: 'Jack',
11                     template: 'template.html'
12                 };
13             }]);
14         })();
15     </script>
16 </head>
17 <body ng-app="ngIncludeTest">
18     <div ng-controller="myController as myCtrl">
19         <div ng-include="info.template"></div>
20     </div>
21 </body>
22 </html>

template.html的代码:

1 <div>
2     <p>This is a template.</p>
3     <p>Your name: {{info.yourname}}</p>
4 </div>

 

好了,讲了这么多常用的Directives,对Directive应该有了更进一步的了解,AngularJS内建了好几十个Directives,基本能满足你所有的需求了,但是如果你提出这么多Directives还是无法满足你的要求,那怎么办呢?

放心,AngularJS框架帮你设计了自定义Directive的方法,不过这篇篇幅已经略大,关于Directive的自定义,还是放到后面一篇去吧,免得大家看得太累了。

由于AngularJS的特性之一就是写出更具语义化的前端代码,最后一个ng-include例子在后面一章也会直接使用自定义的Directive改造一下,不使用div这种不具语义的标签,而使用自定义的语义化标签。

好了,今天就这样吧。

 

参考资料

CodeSchool快速入门视频(英文版):http://campus.codeschool.com/courses/shaping-up-with-angular-js/intro

AngularJS官方文档:https://docs.angularjs.org

posted @ 2015-05-15 08:30  无上@诀  阅读(3481)  评论(6编辑  收藏  举报