Angular内置指令
以ng前缀开头的都是内置指令,因此不要以ng开头命名自定义指令。此外还有其他内置指令在标签中不易发现,如<a>和<form>。
一,布尔属性
<input type="text" ng-model="someProperty" placeholder="TypetoEnable"> <button ng-model="button" ng-disabled="!someProperty">AButton</button>
例二:文本字段会被禁用五秒,直到在 $timeout 中将 isDisabled 属性设置为 true
<textarea ng-disabled="isDisabled">Wait5seconds</textarea> <script> var myapp =angular.module('myapp', []); myapp.run(function($rootScope, $timeout) { $rootScope.isDisabled = true; $timeout(function() { $rootScope.isDisabled = false; }, 5000); }); </script>
2. ng-readonly
表示只读(只能看到,不能修改)的输入域(框)
例子,第一个输入框有文本时第二个输入框只读
Type here to make sibling readonly: <input type="text" ng-model="someProperty"><br/> <input type="text" ng-readonly="someProperty" value="Some text here"/>
3. ng-checked
例,通过 ng-init 指令将 someProperty 的值设置为 true ,将 some Property
同 ng-checked 绑定在一起。
<label>someProperty = {{someProperty}}</label> <input type="checkbox" ng-checked="someProperty" ng-init="someProperty = true" ng-model="someProperty">
4. ng-selected
ng-selected 可以对是否出现 option 标签的 selected 属性进行绑定
<label>Select Two Fish:</label> <input type="checkbox" ng-model="isTwoFish"><br/> <select> <option>One Fish</option> <option ng-selected="isTwoFish">Two Fish</option> </select>
二,类布尔属性
1,ng-href
作用域中的属性动态创建URL,两秒后链接有效
<a ng-href="{{ myHref }}">I'm feeling lucky, when I load</a> <script> angular.module('myApp', []) .run(function($rootScope, $timeout) { $timeout(function() { $rootScope.myHref = 'http://google.com'; }, 2000); }); </script>
2. ng-src
AngularJS会告诉浏览器在 ng-src 对应的表达式生效之前不要加载图像
<h1>WrongWay</h1> <img src="{{imgSrc}}"/> <h1>Rightway</h1> <img ng-src="{{imgSrc}}"/> <script> var myapp =angular.module('myapp', []); myapp.run(function($rootScope, $timeout) { $timeout(function() { $rootScope.imgSrc = 'images/bally.jpg'; }, 2000); }); </script>
三,在指令中使用子作用域
1. ng-app
任何具有 ng-app 属性的DOM元素将被标记为 $rootScope 的起始点。
$rootScope 是作用域链的起始点,任何嵌套在 ng-app 内的指令都会继承它。
2 ng-controller
内置指令 ng-controller 的作用是为嵌套在其中的指令创建一个子作用域,避免将所有操作模型都定义在 $rootScope 上。用这个指令可以在一个DOM元素上放置控制器。ng-controller 接受一个参数 expression ,这个参数是必需的。
3. ng-include
使用 ng-include 可以加载、编译并包含外部HTML片段到当前的应用中.如果你想使用某个特定的作用域,例如 ControllerA 的作用域,必须在同一个DOM元素上添加 ng-controller ="ControllerA"指令,这样当模板加载完成后,不会像往常一样从外部作用域继承并创建一个新的子作用域。
4 ng-switch
这个指令和 ng-switch-when 及 on="propertyName" 一起使用,可以在 propertyName 发生变化时渲染不同指令到视图中。在下面的例子中,在 switch 被调用之前我们用 ng-switch-default 来输出默认值,当 person.name 是Ari时,文本域下面的 div 会显示出来,并且这个人会获得胜利:
<input type="text" ng-model="person.name"/> <div ng-switch on="person.name"> <p ng-switch-default>And the winner is</p> <h1 ng-switch-when="Ari">{{ person.name }}</h1> </div>
5. ng-view
ng-view 指令用来设置将被路由管理和放置在HTML中的视图的位置.
6.ng-if
使用 ng-if 指令可以完全根据表达式的值在DOM中生成或移除一个元素。如果赋值给 ng-if
的表达式的值是 false ,那对应的元素将会从DOM中移除,否则对应元素的一个克隆将被重新插
入DOM中。
ng-if 同 no-show 和 ng-hide 指令最本质的区别是,它不是通过CSS显示或隐藏DOM节点,而
是真正生成或移除节点。
当一个元素被 ng-if 从DOM中移除,同它关联的作用域也会被销毁。而且当它重新加入DOM
中时,会通过原型继承从它的父作用域生成一个新的作用域。
<div ng-if="2+2===5"> Won't see this DOM node, not even in the source code </div> <div ng-if="2+2===4"> Hi, I do exist </div>
7. ng-repeat
ng-repeat 用来遍历一个集合或为集合中的每个元素生成一个模板实例。集合中的每个元素
都会被赋予自己的模板和作用域。同时每个模板实例的作用域中都会暴露一些特殊的属性。
$index :遍历的进度(0... length-1 )。
$first :当元素是遍历的第一个时值为 true 。
$middle :当元素处于第一个和最后元素之间时值为 true 。
$last :当元素是遍历的最后一个时值为 true 。
$even :当 $index 值是偶数时值为 true 。
$odd :当 $index 值是奇数时值为 true 。
例:创建列表
<ul ng-controller="PeopleController"> <li ng-repeat="person in people" ng-class="{even: $even, odd: $odd}"> {{person.name}} lives in {{person.city}} </li> </ul>
.odd { background-color: blue; } .even { background-color: red; }
myapp.controller('PeopleController',function($scope) { $scope.people = [ {name: "Ari", city: "San Francisco"}, {name: "Erik", city: "Seattle"} ]; });
8. ng-init
ng-init 指令用来在指令被调用时设置内部作用域的初始状态。
<div ng-init="greeting='Hello';person='World'"> {{greeting}} {{person}} </div>
9. {{ }}
<div>{{name}}</div>
{{ }} 语法是AngularJS内置的模板语法,它会在内部 $scope 和视图之间创建绑定。基于这个绑定,只要 $scope 发生变化,视图就会随之自动更新。事实上它也是指令,虽然看起来并不像,实际上它是 ng-bind 的简略形式,用这种形式不需要创建新的元素,因此它常被用在行内文本中。
注意,在屏幕可视的区域内使用 {{ }} 会导致页面加载时未渲染的元素发生闪烁,用 ng-bind可以避免这个问题。
<div ng-init="greeting='HelloWorld'"> <p ng-bind="greeting"></p> </div>
10. ng-bind
尽管可以在视图中使用 {{ }} 模板语法(AngularJS内置的方式),我们也可以通过 ng-bind
指令实现同样的行为。
<div ng-init="greeting='HelloWorld'"> <p ng-bind="greeting"></p> </div>
11. ng-cloak
除使用 ng-bind 来避免未渲染元素闪烁,还可以在含有 {{ }} 的元素上使用 ng-cloak 指令ng-cloak 指令会将内部元素隐藏,直到路由调用对应的页面时才显示出来
<div ng-init="greeting='HelloWorld'"> <p ng-cloak>{{ greeting }}</p> </div>
12. ng-bind-template
同 ng-bind 指令类似, ng-bind-template 用来在视图中绑定多个表达式。
<div ng-bind-template="{{message}}{{name}}"> </div>
13. ng-model
ng-model 指令用来将 input 、 select 、 text area 或自定义表单控件同包含它们的作用域中的属性进行绑定。它可以提供并处理表单验证功能,在元素上设置相关的CSS类( ng-valid 、
ng-invalid 等),并负责在父表单中注册控件。
14. ng-show/ng-hide
ng-show 和 ng-hide 根据所给表达式的值来显示或隐藏HTML元素。当赋值给 ng-show 指令的值为 false 时元素会被隐藏。类似地,当赋值给 ng-hide 指令的值为 true 时元素也会被隐藏。
<div ng-show="2 + 2 == 5"> 2 + 2 isn't 5, don't show </div> <div ng-show="2 + 2 == 4"> 2 + 2 is 4, do show </div> <div ng-hide="2 + 2 == 5"> 2 + 2 isn't 5, don't hide </div> <div ng-hide="2 + 2 == 4"> 2 + 2 is 4, do hide </div>
15. ng-change
这个指令会在表单输入发生变化时计算给定表达式的值。因为要处理表单输入,这个指令要和 ngModel 联合起来使用。
例:只要文本输入字段中的内容发生了变化就会改变 equation.x 的值,进而运
行 change() 函数。
<div ng-controller="EquationController"> <input type="text" ng-model="equation.x" ng-change="change()" /> <code>{{ equation.output }}</code> </div>
myapp.controller('EquationController',function($scope) { $scope.equation = {}; $scope.change = function() { $scope.equation.output = parseInt($scope.equation.x) + 2; }; });
16. ng-form
ng-form 用来在一个表单内部嵌套另一个表单。普通的HTML <form> 标签不允许嵌套,但
ng-form 可以。
下面的CSS类会根据表单的验证状态自动设置:
表单合法时设置 ng-valid ;
表单不合法时设置 ng-invlid ;
表单未进行修改时设置 ng-pristion ;
表单进行过修改时设置 ng-dirty 。
Angular不会将表单提交到服务器,除非它指定了 action 属性。要指定提交表单时调用哪个
JavaScript方法,使用下面两个指令中的一个。
ng-submit :在表单元素上使用。
ng-click :在第一个按钮或 submit 类型( input[type=submit] )的输入字段上使用。
为了避免处理程序被多次调用,只使用下面两个指令中的一个。
示例:
<form name="signup_form" ng-controller="FormController" ng-submit="submitForm()" novalidate> <div ng-repeat="field in fields" ng-form="signup_form_input"> <input type="text" name="dynamic_input" ng-required="field.isRequired" ng-model="field.name" placeholder="{{field.placeholder}}" /> <div ng-show="signup_form_input.dynamic_input.$dirty && signup_form_input.dynamic_input.$invalid"> <span class="error" ng-show="signup_form_input.dynamic_input.$error.required"> The field is required. </span> </div> </div> <button type="submit" ng-disabled="signup_form.$invalid"> Submit All </button> </form>
input.ng-invalid { border: 1px solid red; } input.ng-valid { border: 1px solid green; }
myapp.controller('FormController',function($scope) { $scope.fields = [ {placeholder: 'Username', isRequired: true}, {placeholder: 'Password', isRequired: true}, {placeholder: 'Email (optional)', isRequired: false} ]; $scope.submitForm = function() { alert("it works!"); }; });
17. ng-click
ng-click 用来指定一个元素被点击时调用的方法或表达式。
例:加减
<div ng-controller="CounterController"> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> count: {{ count }} <button ng-click="decrement()"> Decrement </button> <div>
myapp.controller('CounterController', function($scope) { $scope.decrement = function() { $scope.count = $scope.count - 1; }; })
18. ng-select
ng-select 用来将数据同HTML的 <select> 元素进行绑定。这个指令可以和 ng-model 以及ng-options 指令一同使用,构建精细且表现优良的动态表单。
ng-options 的值可以是一个内涵表达式(comprehension expression),其实这只是一种有趣
的说法,简单来说就是它可以接受一个数组或对象,并对它们进行循环,将内部的内容提供给
select 标签内部的选项。它可以是下面两种形式。
数组作为数据源:
用数组中的值做标签;
用数组中的值作为选中的标签;
用数组中的值做标签组;
用数组中的值作为选中的标签组。
对象作为数据源:
用对象的键值(key-value)做标签;
用对象的键值作为选中的标签;
用对象的键值作为标签组;
用对象的键值作为选中的标签组。
下面看一个 ng-select 指令的实例:
<div ng-controller="CityController"> <select ng-model="city" ng-options="city.name for city in cities"> <option value="">Choose City</option> </select> Best City: {{ city.name }} </div>
myapp.controller('CityController',function($scope) { $scope.cities = [ {name: 'Seattle'}, {name: 'San Francisco'}, {name: 'Chicago'}, {name: 'New York'}, {name: 'Boston'} ]; });
19. ng-submit
ng-submit 用来将表达式同 onsubmit 事件进行绑定。这个指令同时会阻止默认行为(发送请
求并重新加载页面),除非表单不含有 action 属性。
<form ng-submit="submit()" ng-controller="FormController"> Enter text and hit enter: <input type="text" ng-model="person.name" name="person.name" /> <input type="submit" name="person.name" value="Submit" /> <code>people={{people}}</code> <ul ng-repeat="(index, object) in people"> <li>{{ object.name }}</li> </ul> </form>
myapp.controller('FormController',function($scope) { $scope.person = { name: null }; $scope.people = []; $scope.submit = function() { if ($scope.person.name) { $scope.people.push({name: $scope.person.name}); $scope.person.name = ''; } }; });
20. ng-class
使用 ng-class 动态设置元素的类,方法是绑定一个代表所有需要添加的类的表达式。重复
的类不会添加。当表达式发生变化,先前添加的类会被移除,新类会被添加。
例:用 ng-class 在一个随机数大于5时将 .red 类添加到一个 div 上
<div ng-controller="LotteryController"> <div ng-class="{red: x > 5}" ng-if="x > 5"> You won! </div> <button ng-click="x = generateNumber()" ng-init="x = 0"> Draw Number </button> <p>Number is: {{ x }}</p> </div>
.red { background-color: red; }
angular.module('myApp',[]) .controller('LotteryController', function($scope) { $scope.generateNumber = function() { return Math.floor((Math.random()*10)+1); }; });
21. ng-attr-(suffix)
当AngularJS编译DOM时会查找花括号 {{ some expression }} 内的表达式。这些表达式会
被自动注册到 $watch 服务中并更新到 $digest 循环中,成为它的一部分:
<-- updated when`someExpression` on the$scope
is updated -->
<h1>Hello{{someExpression}}</h1>
有时浏览器会对属性会进行很苛刻的限制。SVG就是一个例子:
<svg>
<circle cx="{{ cx }}"></circle>
</svg>
运行上面的代码会抛出一个错误,指出我们有一个非法属性。可以用 ng-attr-cx 来解决这
个问题。注意, cx 位于这个名称的尾部。在这个属性中,通过用 {{ }} 来写表达式,达到前面提
到的目的。
<svg>
<circle ng-attr-cx="{{ cx }}"><circle>
</svg>