$attrs 是自訂 directive 存取元素屬性的入口。它不只是「讀值」這麼簡單,還能監聽變化($observe)與主動寫入($set)。本文透過一個涵蓋多種 directive 型態的範例,把常用操作整理清楚。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>$attrs 示例</title>
<script src="js/jquery.js"></script>
<script src="js/angular.min.js"></script>
</head>
<body ng-app="Demo">
<div a>a_directive</div>
<div ng-controller="TestCtrl">
<h1 t>原始內容</h1>
<h2 t2>原始內容</h2>
<h3 t3="hiphop" title2="{{name}}">原始內容</h3>
<div compile></div>
<div>
<test a="{{ a }}" b c="xxx"></test>
<button ng-click="a=a+1">修改</button>
</div>
<te a="1" ys-a="123" ng-click="show(1)">這裡</te>
</div>
<script>
var app = angular.module('Demo', [], angular.noop);
app.controller("TestCtrl", function($scope){
$scope.name = "qihao";
});
// 繼承父層 scope
app.directive("t", function() {
return {
controller: function($scope){ $scope.name = "qq" },
template: "<div>test:implementToParent{{name}}</div>",
replace: true,
scope: true // 作用域是繼承的,默認就是繼承的
};
});
// 不繼承(isolate 但 restrict AE)
app.directive("t2", function() {
return {
controller: function($scope){ $scope.name = "nono" },
template: "<div>test:implementToParent{{name}}</div>",
replace: true,
restrict: "AE"
};
});
// 用 @ 綁定屬性字串
app.directive("t3", function() {
return {
template: "<div>titleIs:{{title}}<br>title2Is:{{title2}}</div>",
replace: true,
restrict: "AE",
scope: {
title: "@t3",
title2: "@title2"
}
};
});
// compile / controller / transclude 的组合
app.directive('a', function() {
var func = function() {
console.log('compile');
return function() { console.log('link'); }
}
var controller = function($scope, $element, $attrs, $transclude) {
// $transclude 是指令標籤的複製體
console.log('controller');
console.log($scope);
console.log($transclude);
// $transclude 接受一個函式,可以對這個克隆元素進行操作
var node = $transclude(function(clone_element, scope) {
$element.append(clone_element);
$element.append("<span>spanTag___</span>");
console.log(clone_element);
console.log(scope);
});
console.log(node);
}
return {
compile: func,
template: "<h1 ng-transclude></h1>",
controller: controller,
transclude: true,
restrict: 'AE'
};
});
// pre / post link
app.directive('compile', function() {
var func = function() {
console.log('a compile');
return {
pre: function(){ console.log('a link pre') },
post: function(){ console.log('a link post') }
}
}
return { restrict: "AE", compile: func }
})
// $observe 監聽屬性變化
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;
});
// $set 主動設定屬性
app.directive('te', function(){
var func = function($scope, $element, $attrs, $ctrl){
console.log($ctrl);
$attrs.$set('b', 'ooo');
$attrs.$set('a-b', '11');
// 參數依序為:屬性名、值、是否為 interpolated 屬性、對應的 attribute 名稱
$attrs.$set('c-d', '11', true, 'c_d');
console.log($attrs);
}
return {
compile: function(){ return func },
restrict: 'E'
}
});
app.controller('TestCtrl', function($scope){
$scope.show = function(v){ console.log(v); }
});
</script>
</body>
</html>
範例用 t、t2 兩個 directive 刻意展示差異。scope: true 建立一個「繼承型」子 scope,能讀寫父層的 $scope.name,t 的 controller 把 name 改成 "qq" 後父層也跟著變。不指定 scope(如 t2)則完全不新建 scope,直接共用父層的。而 scope: { ... } 建立隔離 scope(isolate scope),父層的屬性不會污染進來,必須透過 @、=、& 明確聲明要哪些。
scope: { title: "@t3" } 中的 @ 表示「取一次字串值」。注意 "@t3" 的意思是「讀取名为 t3 的屬性」,而不是 name 屬性。t3 的例子裡,title 會得到 "hiphop",title2 因為寫了 {{name}} 插值,所以能隨父 scope 變化而更新。
想在程式碼中監聽這種插值屬性的變化,就用 $attrs.$observe('a', callback)。test directive 示範了這一點:點擊「修改」按鈕讓 a 加一,observe 的 callback 就會被觸發並印出新值。$observe 只能用在插值屬性上,對固定字串不會觸發。
$attrs.$set(name, value) 可以從 directive 內部改寫元素屬性,常用於「讀取後正規化再寫回」。第四個參數 c_d 對應的是 DOM 上實際的屬性寫法,這牽涉到 Angular 的名稱正規化規則:HTML 中的 c-d 會被轉成 camelCase 的 cD 存在 $attrs 裡,反之要寫回 HTML 時又得轉回連字號形式。
把 console 的輸出順序記下來,就能理解 Angular 的編譯流程:
實務上 90% 的場合只需要 link 函式(等同 post-link),因為那時子元素的 DOM 與 directive 都已經準備好。只有需要在子 directive 連結前動手腳時,才需要 pre-link。
transclude: true 搭配模板中的 ng-transclude,可以把 directive 標籤內部的原始內容「搬」到模板指定位置。a directive 透過 controller 注入的 $transclude 函式取得複製體,再自行決定要 append 到哪裡——範例就是先把 clone 塞進去,再補上一個 span。這正是 ng-repeat、ng-if 這類結構型 directive 能運作的核心機制。