AngularJS 指令
AngularJS 通过被称为 指令 的新属性来扩展 HTML。
AngularJS 通过内置的指令来为应用添加功能。
AngularJS 允许你自定义指令。
AngularJS 指令
AngularJS 指令是扩展的 HTML 属性,带有前缀 ng-。
ng-app 指令初始化一个 AngularJS 应用程序。
ng-init 指令初始化应用程序数据。
ng-model 指令把元素值(比如输入域的值)绑定到应用程序。
完整的指令内容可以参阅 AngularJS 参考手册。
AngularJS 实例
尝试一下 »
ng-app 指令告诉 AngularJS,<div> 元素是 AngularJS 应用程序 的"所有者"。
数据绑定
上面实例中的 {{ firstName }} 表达式是一个 AngularJS 数据绑定表达式。
AngularJS 中的数据绑定,同步了 AngularJS 表达式与 AngularJS 数据。
{{ firstName }} 是通过 ng-model="firstName" 进行同步。
在下一个实例中,两个文本域是通过两个 ng-model 指令同步的:
AngularJS 实例
尝试一下 »
![]() |
使用 ng-init 不是很常见。您将在控制器一章中学习到一个更好的初始化数据的方式。 |
|---|
重复 HTML 元素
ng-repeat 指令会重复一个 HTML 元素:
AngularJS 实例
尝试一下 »
ng-repeat 指令用在一个对象数组上:
AngularJS 实例
尝试一下 »
![]() |
AngularJS 完美支持数据库的 CRUD(增加Create、读取Read、更新Update、删除Delete)应用程序。 把实例中的对象想象成数据库中的记录。 |
|---|
ng-app 指令
ng-app 指令定义了 AngularJS 应用程序的 根元素。
ng-app 指令在网页加载完毕时会自动引导(自动初始化)应用程序。
稍后您将学习到 ng-app 如何通过一个值(比如 ng-app="myModule")连接到代码模块。
ng-init 指令
ng-init 指令为 AngularJS 应用程序定义了 初始值。
通常情况下,不使用 ng-init。您将使用一个控制器或模块来代替它。
稍后您将学习更多有关控制器和模块的知识。
ng-model 指令
ng-model 指令 绑定 HTML 元素 到应用程序数据。
ng-model 指令也可以:
- 为应用程序数据提供类型验证(number、email、required)。
- 为应用程序数据提供状态(invalid、dirty、touched、error)。
- 为 HTML 元素提供 CSS 类。
- 绑定 HTML 元素到 HTML 表单。
ng-repeat 指令
ng-repeat 指令对于集合中(数组中)的每个项会 克隆一次 HTML 元素。
创建自定义的指令
除了 AngularJS 内置的指令外,我们还可以创建自定义指令。
你可以使用 .directive 函数来添加自定义的指令。
要调用自定义指令,HTML 元素上需要添加自定义指令名。
使用驼峰法来命名一个指令, runoobDirective, 但在使用它时需要以 - 分割, runoob-directive:
AngularJS 实例
<runoob-directive></runoob-directive>
<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
return {
template : "<h1>自定义指令!</h1>"
};
});
</script>
</body>
尝试一下 »
你可以通过以下方式来调用指令:
- 元素名
- 属性
- 类名
- 注释
以下实例方式也能输出同样结果:
限制使用
你可以限制你的指令只能通过特定的方式来调用。
实例
通过添加 restrict 属性,并设置值为 "A",
来设置指令只能通过属性的方式来调用:
app.directive("runoobDirective", function() {
return {
restrict : "A",
template : "<h1>自定义指令!</h1>"
};
});
尝试一下 »
restrict 值可以是以下几种:
E作为元素名使用A作为属性使用C作为类名使用M作为注释使用
restrict 默认值为 EA, 即可以通过元素名和属性名来调用指令。

Alice
che***0503@163.com
angular自定义指令的两种写法:
上面这种,感觉更清晰明确一点。
// angular.module('MyApp',[]) // .directive('zl1',zl1) // .controller('con1',['$scope',func1]); // // function zl1(){ // var directive={ // restrict:'AEC', // template:'this is the it-first directive', // }; // return directive; // }; // // function func1($scope){ // $scope.name="alice"; // } //这是教程里类似的写法 angular.module('myApp',[]).directive('zl1',[ function(){ return { restrict:'AE', template:'thirective', link:function($scope,elm,attr,controller){ console.log("这是link"); }, controller:function($scope,$element,$attrs){ console.log("这是con"); } }; }]).controller('Con1',['$scope',function($scope){ $scope.name="aliceqqq"; }]);Alice
che***0503@163.com
Alice
che***0503@163.com
还有指令配置项的:link controller等在项目运用中有遇到过:
angular.module('myApp', []).directive('first', [ function(){ return { // scope: false, // 默认值,共享父级作用域 // controller: function($scope, $element, $attrs, $transclude) {}, restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment template: 'first name:{{name}}', }; }]).directive('second', [ function(){ return { scope: true, // 继承父级作用域并创建指令自己的作用域 // controller: function($scope, $element, $attrs, $transclude) {}, restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment //当修改这里的name时,second会在自己的作用域中新建一个name变量,与父级作用域中的 // name相对独立,所以再修改父级中的name对second中的name就不会有影响了 template: 'second name:{{name}}', }; }]).directive('third', [ function(){ return { scope: {}, // 创建指令自己的独立作用域,与父级毫无关系 // controller: function($scope, $element, $attrs, $transclude) {}, restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment template: 'third name:{{name}}', }; }]) .controller('DirectiveController', ['$scope', function($scope){ $scope.name="mike"; }]);Alice
che***0503@163.com
跟我回高老庄
807***326@qq.com
跟我回高老庄
807***326@qq.com
奕溟
zxq***xszwm@163.com
首先,非常感谢Alice提供代码!!
<body ng-app="myApp" ng-controller="YiMing"> 姓名: <input type="text" ng-model="name"/> <br/> <first/> <second/> <script> angular.module('myApp', []).directive('first', [ function(){ return { restrict: 'AE', template: 'first name:{{name}}' }; }]).directive('second', [ function(){ return { scope: {}, // 创建指令自己的独立作用域,与父级毫无关系 controller: function($scope) { $scope.name="YiMing" }, restrict: 'AE', template: 'second name:{{name}}' }; }]).controller('YiMing', ['$scope', function($scope){ $scope.name="YiMing"; }]); </script> </body>尝试一下 »
1. 当同时调用first和second时,只有first生效,两个template不会同时出现。
2. 当设置了 scope:{} 之后,{{name}}获取不到了,原因就是作用域的问题,想要设置这里的name的值,可以再加一个controller的字段。
奕溟
zxq***xszwm@163.com
菜鸟
643***369@qq.com
借用Alice的代码继续 关于自定义的指令内容解读
angular.module('myApp', []).directive('first', [ function(){ return { scope: false, //默认值为 false 共享父作用域 值为true时共享父级作用域并创建指令自己的 controller: function($scope, $element, $attrs, $transclude) {}, //作用域 值为{}时创建全新的隔离作用域, 值为string时为控制器名称 restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment template: 'first name:{{name}}',//值为string、function 用于显示dom元素 templateUrl: 'xxx.html' //值为string function 以id为xxx.html为 调用文件显示 priority: 0 //指明指令的优先级,若在dom上有多个指令优先级高的先执行 replace: flase // 默认值为false 当为true是直接替换指令所在的标签 terminal: true //值为true时优先级低于此指令的其它指令无效 link:function // 值为函数 用来定义指令行为从传入的参数中获取元素并进行处理 }; }]).directive('second', [ function(){ return { scope: true, // controller: function($scope, $element, $attrs, $transclude) {}, restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment //当修改这里的name时,second会在自己的作用域中新建一个name变量,与父级作用域中的 // name相对独立,所以再修改父级中的name对second中的name就不会有影响了 template: 'second name:{{name}}', }; }]) .controller('DirectiveController', ['$scope', function($scope){ $scope.name="mike"; }]);菜鸟
643***369@qq.com
黑绚源
861***478@qq.com
参考地址
templateUrl 除了接受 String,可以接受 function(elem,attr){}。
测试实例:
customer-address.html 文件代码:
Address: {{customer.address}}customer-name.html 文件代码:
Name: {{customer.name}}以下测试代码需要与 customer-address.html 和 customer-name.html 文件在同一个目录下:
angular.module('docsTemplateUrlDirective', []) .controller('Controller', ['$scope', function($scope) { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) .directive('myCustomer', function() { return { templateUrl: function(elem, attr) { return 'customer-' + attr.type + '.html'; } }; });尝试一下 »
黑绚源
861***478@qq.com
参考地址
wade
jaw***e@sina.com
列表调用,还可用于超链接,棒的不行:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script> </head> <body> <div ng-app="" ng-init="names=[ {name:'菜鸟教程', country:'CN', url:'https://www.runoob.com'}, {name:'Google', country:'USA', url:'https://www.google.com'}, {name:'知乎', country:'CN', url:'https://www.zhihu.com'}]"> <p>循环对象:</p> <ul> <a ng-repeat="x in names" href="{{x.url}}" rel="nofollow"> {{ x.name + ', ' + x.country }}<br></a> </ul> </div> </body> </html>尝试一下 »
wade
jaw***e@sina.com
hea7en
882***65@qq.com
有时候绑定
ngModel到一个 getter/setter 函数时很有用的。getter 是一种能返回一个模型表示的无参函数,setter 是只有一个参数的用于设置模型内部状态的函数。 它对于模型内部与视图显示时所用的数据形式不一致时非常有用。要使用它,你需要添加
ng-model-options="{ getterSetter: true }"到一个有ng-model元素上。你也可以添加ng-model-options="{ getterSetter: true }"到<form>上,使的表单中的所有<input>都生效。参见ngModelOptions获取更多信息。下面的例子演示如何通过 getter/setter 使用
ngModel:<div ng-controller="ExampleController"> <form name="userForm"> <label> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ getterSetter: true }" /> </label> </form> <p>user.name = <span ng-bind="user.name()"></span></p> </div>尝试一下 »
hea7en
882***65@qq.com
hea7en
882***65@qq.com
ngInit 指令允许你在执行一个当前域中的表达式,ngInit 只适用于 ngRepeat 这种特殊性质的属性,除此之外,你应该使用控制器 而不是 ngInit 来初始化域中的值。
<body ng-app="initExample"> <script> angular.module('initExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.list = [['a', 'b'], ['c', 'd']]; }]); </script> <div ng-controller="ExampleController"> <div ng-repeat="innerList in list" ng-init="outerIndex = $index"> <div ng-repeat="value in innerList" ng-init="innerIndex = $index"> <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span> </div> </div> </div> </body>尝试一下 »
hea7en
882***65@qq.com
yimawujiang
183***9689@qq.com
奕溟的代码同时调用 first 和 second 两个指令时只有 first 指令生效是因为使用的是单标签,只要把 fist 和 second 都改成双标签即可。如下:
<body ng-app="myApp" ng-controller="YiMing"> 姓名: <input type="text" ng-model="name"/> <br/> <first></first> <second></second> <script> angular.module('myApp', []).directive('first', [ function(){ return { restrict: 'AE', template: 'first name:{{name}}' }; }]).directive('second', [ function(){ return { scope: {}, // 创建指令自己的独立作用域,与父级毫无关系 controller: function($scope) { $scope.name="YiMing" }, restrict: 'AE', template: 'second name:{{name}}' }; }]).controller('YiMing', ['$scope', function($scope){ $scope.name="YiMing"; }]); </script> </body>尝试一下 »
yimawujiang
183***9689@qq.com