AngularJS 通过被称为 指令 的新属性来扩展 HTML。
AngularJS 允许你自定义指令。
AngularJS 指令
AngularJS 指令是扩展的 HTML 属性,带有前缀 ng-。
ng-app 指令初始化一个 AngularJS 应用程序。
ng-init 指令初始化应用程序数据。
ng-model 指令把元素值(比如输入域的值)绑定到应用程序。
ng-repeat 指令会重复一个 HTML 元素:
<!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:‘Jani‘,country:‘Norway‘},{name:‘Hege‘,country:‘Sweden‘},{name:‘Kai‘,country:‘Denmark‘}]"> <p>循环对象:</p> <ul> <li ng-repeat="x in names"> {{ x.name + ‘,‘ + x.country }}</li> </ul> </div> </body> </html>
创建自定义的指令
除了 AngularJS 内置的指令外,我们还可以创建自定义指令。
使用驼峰法来命名一个指令, runoobDirective,但在使用它时需要以 - 分割, runoob-directive:
<!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 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> </html>
注意: 我们需要在该实例添加 replace 属性, 否则评论是不可见的。
注意: 你必须设置 restrict 的值为 "M" 才能通过注释来调用指令。
restrict 值可以是以下几种:
// E = Element,A = Attribute,C = Class,M = Comment
restrict 默认值为 EA@H_502_92@,即可以通过元素名和属性名来调用指令。
使用方法
元素名
<runoob-directive></runoob-directive>
<div runoob-directive></div>
类名
<div class="runoob-directive"></div>
注释
<!-- directive: runoob-directive -->
ok
摘自:http://www.runoob.com/angularjs/angularjs-directives.html