整个 Attributes 对象是比较简单的,它的成员包括了:
- $$element 属性所在的节点。
- $attr 所有的属性值(类型是对象)。
- $normalize 一个名字标准化的工具函数,可以把 变成
ngClick
。 - $observe 为属性注册侦听器的函数。
- $set 设置对象属性,及节点属性的工具。
先看 $observe 的使用,基本上相当于 $scope 中的 $watch :
- var app = angular.module('Demo', [], angular.noop);
app.directive('test', function(){
var func = function($element, $attrs){
console.log($attrs);
$attrs.$observe('a', function(new_v){
console.log(new_v);
});
}
return {compile: func,
restrict: 'E'}
});
app.controller('TestCtrl', function($scope){
$scope.a = 123;
});
- value 需要设置的值。
- attrName 实际的属性名,与“标准化”之后的属性名有区别。
从例子中可以看到,原始的节点属性值对,放到对象中之后,名字一定是“标准化”之后的。但是手动 的新属性,不会自动做标准化处理。