anjularjs direction 指令:
ng-app: 指令初始化一个anjularjs应用程序:定义在什么范围内使用
定义了angularjs 的应用程序跟元素 ng-app 通过一个值(比如 ng-app="myModule")连接到代码模块。指令在页面加载完毕时自动引导(自动初始化)应用程序
ng-init: 指令初始化程序数据:进行初始值,通常情况下使用控制器或模块来代替他
ng-model:指令把元素值(比如输入域的值) :绑定到应用程序 :
ng-model 指令也可以:
- 为应用程序数据提供类型验证(number、email、required)。
- 为应用程序数据提供状态(invalid、dirty、touched、error)。
- 为 HTML 元素提供 CSS 类。
- 绑定 HTML 元素到 HTML 表单。
<h2>价格计算器</h2>
数量: <input type="number" ng-model="quantity">
价格: <input type="number" ng-model="price">
<p><b>总价:</b> {{quantity * price}}</p>
</div>
2:重复html指令
ng-repeat: 指令会重复一个html元素
使用ng-repeat循环显示数组
ng-bind 指令需要放在标签中使用否则,不会显示想要的结果输出
<p>用ng-repeat来循环数组</p>
<ul>
<li ng-repeat="x in names" >
<span ng-bind="x"></span>
<%--{{x}}--%>
</li>
</ul>
</div>
循环数组
<div ng-app="" ng-init="names=[
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<p>循环对象:</p>
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
3:创建自定义指令
.directive 函数添加自定义指令 针对于自定义标签
要调用自定义指令,HTMl 元素上需要添加自定义指令名。
使用驼峰法来命名一个指令, runoobDirective, 但在使用它时需要以 - 分割, runoob-directive:
<body ng-app="myApp">
<runoob-directive></runoob-directive>
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
template : "<h1>自定义指令!</h1>"
};
});
</script>
</body>
derective 的第一个参数的名字就是自定义的标签
通过元素名调用指令
<body ng-app="myApp">
<runoob-directive></runoob-directive>
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
template : "<h1>自定义指令!</h1>"
};
});
</script>
</body>
通过属性名来调用函数
<body ng-app="myApp">
<div runoob-directive></div>
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
template : "<h1>自定义指令!</h1>"
};
});
</script>
</body>
</body>
通过类名 调用指令
<body ng-app="myApp">
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
restrict : "C",
template : "<h1>自定义指令!</h1>"
};
});
</script>
<p><strong>注意:</strong> 你必须设置 <b>restrict</b> 的值为 "C" 才能通过类名来调用指令。</p>
通过注释调用指令
注意: 我们需要在该实例添加 replace 属性, 否则评论是不可见的。
注意: 你必须设置 restrict 的值为 "M" 才能通过注释来调用指令。
<body ng-app="myApp">
<!-- directive: runoob-directive -->
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
restrict : "M",
replace : true,
template : "<h1>自定义指令!</h1>"
};
});
</script>
<p><strong>注意:</strong> 我们需要在该实例添加 <strong>replace</strong> 属性, 否则评论是不可见的。</p>
<p><strong>注意:</strong> 你必须设置 <b>restrict</b> 的值为 "M" 才能通过注释来调用指令。</p>
</body>
通过设置 restrict 属性值为 "A" 来设置指令只能通过 HTML 元素的属性来调用。
restrict 值可以是以下几种:
E
只限元素名使用A
只限属性使用C
只限类名使用M
只限注释使用