AngularJS指令
ng-app指令
ng-app 指令告诉 AngularJS,<div> 元素是 AngularJS 应用程序 的"所有者"。ng-app 指令定义了 AngularJS 应用程序的 根元素。
ng-app 指令在网页加载完毕时会自动引导(自动初始化)应用程序。
ng-init 指令
ng-init 指令为 AngularJS 应用程序定义了 初始值。
通常情况下,不使用 ng-init。您将使用一个控制器或模块来代替它。
ng-model 指令
ng-model 指令 绑定 HTML 元素 到应用程序数据。
<div ng-app="" ng-init="quantity=1;price=5">
<h2>价格计算器</h2>
数量:<input type="number" ng-model="quantity">
价格:<input type="number" ng-model="price">
<p>总价:{{ quantity*price}}</p>
</div>
ng-model 指令也可以:
为应用程序数据提供类型验证(number、email、required)。
为应用程序数据提供状态(invalid、dirty、touched、error)。
为 HTML 元素提供 CSS 类。
绑定 HTML 元素到 HTML 表单。
ng-repeat指令
ng-repeat 指令对于集合中(数组中)的每个项会 克隆一次 HTML 元素。
<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'}]">
<ul>
<li ng-repeat="x in names">
{{ x.name+","+x.country }}
</li>
</ul>
</div>
创建自定义指令
使用 .directive 函数来添加自定义的指令。
要调用自定义指令,HTML 元素上需要添加自定义指令名。
使用驼峰法来命名一个指令, runoobDirective, 但在使用它时需要以 - 分割, runoob-directive:
自定义指令调用方法
1、元素名
<body ng-app="myApp">
<runoob-directive></runoob-directive>
<script>
var app=angular.module("myApp",[]);
app.directive("runoobDirective",function(){
return {
template:"<h1>自定义指令</h1>"
};
});
</script>
</body>
2、属性
<body ng-app="myApp">
<div runoob-directive></div>
<script>
var app=angular.module("myApp",[]);
app.directive("runoobDirective",function(){
return {
template:"<h1>自定义指令</h1>"
};
});
</script>
</body>
3、类名
<body ng-app="myApp">
<div class="runoob-directive"></div>
<script>
var app=angular.module("myApp",[]);
app.directive("runoobDirective",function(){
return {
<!-- 必须设置 restrict 的值为 "C" 才能通过类名来调用指令 -->
restrict:"C",
template:"<h1>自定义指令</h1>"
};
});
</script>
</body>
4、注释
<body ng-app="myApp">
<!--directive: runoob-directive -->
<script>
var app=angular.module("myApp",[]);
app.directive("runoobDirective",function(){
return {
<!-- 添加 replace 属性, 否则评论是不可见的 -->
<!-- 必须设置 restrict 的值为 "M" 才能通过注释来调用指令-->
restrict:"M",
replace:true,
template:"<h1>自定义指令</h1>"
};
});
</script>
</body>
限制使用
你可以限制你的指令只能通过特定的方式来调用。
设置 restrict 属性值为 “A” 来设置指令只能通过 HTML 元素的属性来调用。
restrict 的值
restrict 值可以是以下几种:
- E 作为元素名使用
- A 作为属性使用
- C 作为类名使用
- M 作为注释使用
** restrict 默认值为 EA, 即可以通过元素名和属性名来调用指令. **