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

常用的Directives

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

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

 <!DOCTYPE html>
<html>
<head>
<script src="/Scripts/angular.js"></script>
<script type="text/javascript">
(function () {
var app = angular.module('student', []); // 这次定义一个数组students,里面有三个学生Jack、Mary、Tom
var students = [{
name: "Jack",
age: 18,
sex: 'male',
displayComment: false
},
{
name: "Mary",
age: 16,
sex: 'female',
displayComment: true
},
{
name: "Tom",
age: 17,
sex: 'male',
displayComment: true
}]; app.controller('myController', function () {
this.students = students;
});
})();
</script>
</head>
<body ng-app="student">
<div ng-controller="myController as myCtrl">
<!--使用ng-repeat,优雅的迭代显示所有学生信息-->
<div ng-repeat="stu in myCtrl.students">
<p>Student{{myCtrl.students.indexOf(stu) + 1}}:</p>
<p>Name:{{stu.name}}</p>
<p>Age:{{stu.age}} will be {{stu.age+15}} after 15 years.</p>
<p>Sex:{{stu.sex}}</p>
<p ng-show="stu.displayComment">Comments:This will not display on page.</p>
<br />
</div>
</div>
</body>
</html>

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

 <!DOCTYPE html>
<html>
<head>
<script src="/Scripts/angular.js"></script>
</head>
<body ng-app>
<input ng-model="yourname" />
<br />
Your name is: {{yourname}}
</body>
</html>

3. ng-src & ng-href:

 <!DOCTYPE html>
<html>
<head>
<script src="/Scripts/angular.js"></script>
<script type="text/ecmascript">
(function () {
// 注意,这个demo中我们使用连缀的形式书写代码,这个和以前不一样
// 个人认为连缀的形式没有单独书写清晰
angular.module('src.href.test', [])
.controller('myController', function () {
this.imgName = "112348515178380.png";
});
})();
</script>
</head>
<body ng-app="src.href.test">
<div ng-controller="myController as myCtrl">
<a href="https://images0.cnblogs.com/blog2015/455688/201505/112348515178380.png">A link</a>
<br />
<img src="https://images0.cnblogs.com/blog2015/455688/201505/112348515178380.png" />
<br />
myCtrl.imgName : {{myCtrl.imgName}}
<br />
<a href="https://images0.cnblogs.com/blog2015/455688/201505/{{myCtrl.imgName}}">A link</a>
<br />
<img src="https://images0.cnblogs.com/blog2015/455688/201505/{{myCtrl.imgName}}" />
</div>
</body>
</html>

特别注意:按照官方的说法,直接使用src或者href属性时,由于渲染页面时,AngularJS还没开始解析src或者href中的Expression,因此将会得到一个404错误(因为地址直接被解析成了https://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):

 <!DOCTYPE html>
<html>
<head>
<script src="/Scripts/angular.js"></script>
<script type="text/javascript">
(function () {
var app = angular.module('clicktest', []); app.controller('myController', ['$scope', function ($scope) {
this.sayHello = function () {
alert("Hello, " + $scope.yourname);
};
}]); // 以下代码与上面的功能一样,但是推荐上面这种写法,今后讲AngularJS的服务的时候将会讲到。
// 主要原因是js可以被压缩、加密等操作,$scope 将被变换从而AngularJS无法识别它, 但字符串 '$scope' 是不会被变换的
//app.controller('myController', function ($scope) {
// this.sayHello = function () {
// alert("Hello, " + $scope.yourname);
// };
//});
})();
</script>
</head>
<body ng-app="clicktest">
<div ng-controller="myController as myCtrl">
<input ng-model="yourname" />
<br />
<button ng-click="myCtrl.sayHello()">Say Hello</button>
</div>
</body>
</html>

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

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

 <!DOCTYPE html>
<html>
<head>
<style type="text/css">
.odd {
color: red;
} .even {
color: blue;
} .green_bold {
color: green;
font-weight: bold;
}
</style> <script src="/Scripts/angular.js"></script>
<script type="text/javascript">
(function () {
var app = angular.module('student', []); var students = [{
name: "Jack",
age: 18,
sex: 'male',
displayComment: false
},
{
name: "Mary",
age: 16,
sex: 'female',
displayComment: true
},
{
name: "Tom",
age: 17,
sex: 'male',
displayComment: true
}]; app.controller('myController', function () {
this.students = students;
});
})();
</script>
</head>
<body ng-app="student">
<div ng-init="myVar='green_bold'">
<p ng-class="myVar">This should be green.</p>
</div>
<div ng-controller="myController as myCtrl">
<!--这里添加了 ng-class-odd 和ng-class-even 属性-->
<div ng-repeat="stu in myCtrl.students" ng-class-odd="'odd'" ng-class-even="'even'">
<p>Student{{myCtrl.students.indexOf(stu) + 1}}:</p>
<p>Name:{{stu.name}}</p>
<p>Age:{{stu.age}} will be {{stu.age+15}} after 15 years.</p>
<p>Sex:{{stu.sex}}</p>
<p ng-show="stu.displayComment">Comments:This will not display on page.</p>
<br />
</div>
</div>
</body>
</html>

 

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

 <!DOCTYPE html>
<html>
<head>
<script src="/Scripts/angular.js"></script>
<script type="text/javascript">
(function () {
var app = angular.module('submitExample', []); app.controller('ExampleController', ['$scope', function ($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function () {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
}
};
}]);
})();
</script>
</head>
<body ng-app="submitExample">
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</body>
</html>

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

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

 <!DOCTYPE html>
<html>
<head>
<script src="/Scripts/angular.js"></script>
<script type="text/javascript">
(function () {
var app = angular.module('ngIncludeTest', []);
app.controller('myController', ['$scope', function ($scope) {
$scope.info = {
yourname: 'Jack',
template: 'template.html'
};
}]);
})();
</script>
</head>
<body ng-app="ngIncludeTest">
<div ng-controller="myController as myCtrl">
<div ng-include="info.template"></div>
</div>
</body>
</html>

template.html的代码:

 <div>
<p>This is a template.</p>
<p>Your name: {{info.yourname}}</p>
</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

AngularJS常用Directives实例的更多相关文章

  1. 带你走近AngularJS - 体验指令实例

    带你走近AngularJS系列: 带你走近AngularJS - 基本功能介绍 带你走近AngularJS - 体验指令实例 带你走近AngularJS - 创建自定义指令 ------------- ...

  2. AngularJS常用插件与指令收集

    angularjs 组件列表 bindonce UI-Router Angular Tree angular-ngSanitize模块-$sanitize服务详解 使用 AngularJS 开发一个大 ...

  3. angularjs的resource实例对象

    angularjs的resource实例对象 我们看看都有啥 而直接使用service对象的时候没有前面这些$

  4. windows phone 8.1常用启动器实例

    ---恢复内容开始--- 小梦今天给大家分享一下windows phone 8.1常用启动器实例,包括: 电话启动器 短信启动器 邮件启动器 添加约会|备忘到日历 地图启动器 地图路线启动器 wind ...

  5. AngularJS进阶(十二)AngularJS常用知识汇总(不断更新中....)

    AngularJS常用知识汇总(不断更新中....) 注:请点击此处进行充电! app.controller('editCtrl',['$http','$location','$rootScope', ...

  6. Vue基础进阶 之 常用的实例属性

    Vue实例属性: vue实例直接调用的属性: 常用的实例属性: vm.$data:获取属性: vm.$el:获取实例挂载的元素: vm.$options:获取自定义选项/属性: vm.$refs:获取 ...

  7. C++中vector容器的常用操作方法实例总结

    C++中vector容器的常用操作方法实例总结 参考 1. C++中vector容器的常用操作方法实例总结: 完

  8. 轻量级HTTP服务器Nginx(常用配置实例)

    轻量级HTTP服务器Nginx(常用配置实例)   文章来源于南非蚂蚁   Nginx作为一个HTTP服务器,在功能实现方面和性能方面都表现得非常卓越,完全可以与Apache相媲美,几乎可以实现Apa ...

  9. 【转贴】Windows常用命令实例

    Windows常用命令实例 https://www.cnblogs.com/linyfeng/p/6261629.html 熟练使用DOS常用命令有助于提高工作效率. 1.windows+R:打开运行 ...

随机推荐

  1. 2018.09.23 bzoj3143: [Hnoi2013]游走(dp+高斯消元)

    传送门 显然只需要求出所有边被经过的期望次数,然后贪心把边权小的边定城大的编号. 所以如何求出所有边被经过的期望次数? 显然这只跟边连接的两个点有关. 于是我们只需要求出两个点被经过的期望次数. 对于 ...

  2. hdu -1114(完全背包)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1114 思路:求出存钱罐装全部装满情况下硬币的最小数量,即求出硬币的最小价值.转换为最小背包的问题. # ...

  3. gj5 自定义序列类

    5.1 序列类型的分类 容器序列  list.tuple.deque扁平序列[同一种数据类型]  str.bytes.bytearray.array.array可变序列  list, deque,by ...

  4. LA 3708 && POJ 3154 Graveyard (思维)

    题意:在周长为10000的圆上等距分布着n个雕塑,现在又加入m个,现在让m+n个等距分布,那就得移动一些原有的雕塑,问你移动的最少总距离是多少. 析:首先我们可以知道,至少有一个雕塑是可以不用移动的, ...

  5. timescale

    `timescale 1ns/100ps     表示时延单位为1ns, 时延精度为100ps.`timescale 编译器指令在模块说明外部出现, 并且影响后面所有的时延值.

  6. struts2 file

    JavaBean 中: private File[] pic; private String[] picContentType; private String [] picFileName; sett ...

  7. 01-html和head介绍

    一.web标准 web准备介绍: w3c:万维网联盟组织,用来制定web标准的机构(组织) web标准:制作网页遵循的规范 web准备规范的分类:结构标准.表现标准.行为标准. 结构:html.表示: ...

  8. hdu 5066 小球碰撞(物理题)

    http://acm.hdu.edu.cn/showproblem.php?pid=5066 中学物理题 #include <cstdio> #include <cstdlib> ...

  9. Linux内存子系统及常用调优参数

    1>内存子系统 1>组件: slab    allocator buddy    system kswapd pdflush 2>虚拟化环境: PA:进程地址: HA:虚拟机地址: ...

  10. Hibernate的查询方式汇总

    分别是HQL查询,对象化查询Criteria方法,动态查询DetachedCriteria,例子查询,sql查询,命名查询. 如果单纯的使用hibernate查询数据库只需要懂其中的一项就可以完成想要 ...