加载中...

Attributes的细节


18.9. Attributes的细节

节点属性被包装之后会传给 compilelink 函数。从这个操作中,我们可以得到节点的引用,可以操作节点属性,也可以为节点属性注册侦听事件。

  1. <test a="1" b c="xxx"></test>
  2. var app = angular.module('Demo', [], angular.noop);
  3. app.directive('test', function(){
  4. var func = function($element, $attrs){
  5. console.log($attrs);
  6. }
  7. return {compile: func,
  8. restrict: 'E'}

整个 Attributes 对象是比较简单的,它的成员包括了:

$$element 属性所在的节点。$attr 所有的属性值(类型是对象)。$normalize 一个名字标准化的工具函数,可以把 ng-click 变成 ngClick$observe 为属性注册侦听器的函数。$set 设置对象属性,及节点属性的工具。
除了上面这些成员,对象的成员还包括所有属性的名字。

先看 $observe 的使用,基本上相当于 $scope 中的 $watch

  1. <div ng-controller="TestCtrl">
  2. <test a="{{ a }}" b c="xxx"></test>
  3. <button ng-click="a=a+1">修改</button>
  4. </div>
  5. var app = angular.module('Demo', [], angular.noop);
  6. app.directive('test', function(){
  7. var func = function($element, $attrs){
  8. console.log($attrs);
  9. $attrs.$observe('a', function(new_v){
  10. console.log(new_v);
  11. });
  12. }
  13. return {compile: func,
  14. restrict: 'E'}
  15. });
  16. app.controller('TestCtrl', function($scope){
  17. $scope.a = 123;
  18. });

$set 方法的定义是: function(key, value, writeAttr, attrName) { ... }

  • key 对象的成员名。
  • value 需要设置的值。
  • writeAttr 是否同时修改 DOM 节点的属性(注意区别“节点”与“对象”),默认为 true
  • attrName 实际的属性名,与“标准化”之后的属性名有区别。

    这里

    var app = angular.module('Demo', [], angular.noop);

    app.directive('test', function(){
    var func = function($element, $attrs){
    $attrs.$set('b', 'ooo');
    $attrs.$set('a-b', '11');
    $attrs.$set('c-d', '11', true, 'c_d');
    console.log($attrs);
    }

    1. return {compile: func,
    2. restrict: 'E'}

    });

    app.controller('TestCtrl', function($scope){
    $scope.show = function(v){console.log(v);}
    });

从例子中可以看到,原始的节点属性值对,放到对象中之后,名字一定是“标准化”之后的。但是手动 $set 的新属性,不会自动做标准化处理。


还没有评论.