Page 77 - AngularJS权威教程
P. 77
9.1 基础 ng 属性指令 57
①
根据HTML标准的定义 ,布尔属性代表一个true或false值。当这个属性出现时,这个属性 1
的值就是true(无论实际定义的值是什么)。如果未出现,这个属性的值就是false。
当在AngularJS中使用动态数据绑定时,不能简单地将这个属性值设置为ture或false,因为 2
根据标准定义只有当这个属性不出现时,它的值才为false。因此AngularJS提供了一组带有ng-
前缀版本的布尔属性,通过运算表达式的值来决定在目标元素上是插入还是移除对应的属性。
3
1. ng-disabled
使用ng-disabled可以把disabled属性绑定到以下表单输入字段上: 4
<input> (text、checkbox、radio、number、url, email、submit);
<textarea>; 5
<select>;
<button>。
6
当写普通的HTML输入字段时,如果在元素标签上出现了disabled属性就会禁用这个输入字
段。通过ng-disabled可以对是否出现属性进行绑定。例如,在下面的例子中按钮会一直禁用, 7
直到用户在文本字段中输入内容:
<input type="text" ng-model="someProperty" placeholder="TypetoEnable"> 8
<button ng-model="button" ng-disabled="!someProperty">AButton</button>
在下面的例子,文本字段会被禁用五秒,直到在$timeout中将isDisabled属性设置为true:
9
<textarea ng-disabled="isDisabled">Wait5seconds</textarea>
angular.module('myApp', []) 10
.run(function($rootScope, $timeout) {
$rootScope.isDisabled = true;
$timeout(function() {
$rootScope.isDisabled = false; 11
}, 5000);
});
两个例子的在线示例:http://jsbin.com/iHiYItu/1/edit。 12
2. ng-readonly
13
同其他布尔属性一样,HTML定义只会检查readonly属性是否出现,而不是它的实际值。
通过ng-readonly可以将某个返回真或假的表达式同是否出现readonly属性进行绑定:
14
Type here to make sibling readonly:
<input type="text" ng-model="someProperty"><br/>
<input type="text" 15
ng-readonly="someProperty"
value="Some text here"/>
16
3. ng-checked
标准的checked属性是一个布尔属性,不需要进行赋值。通过ng-checked将某个表达式同是
否出现checked属性进行绑定。 17
—————————— 18
① http://www.w3.org/html/wg/drafts/html/master/infrastructure.html#boolean-attribute