span
ディレクティブを指定する要素を含むこの HTML があります。
<div ng-controller="MyCtrl">
<span id="theSpan" my-directive="{{data.one}}" title="{{data.two}}">
</div>
ディレクティブは、いくつかの HTML を要素に追加します。
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function() {
return {
template: "<div>{{text}}</div>",
scope: {
text: "@myDirective"
}
};
});
function MyCtrl($scope) {
$scope.data = {
one: 'One!!',
two: 'Two!!'
};
}
このコードは、次の DOM 構造になります。
<div ng-controller="MyCtrl" class="ng-scope">
<span id="theSpan" my-directive="One!!" title="" class="ng-isolate-scope ng-scope">
<div class="ng-binding">One!!</div>
</span>
</div>
title
問題は、 の属性のデータが欠落していることspan
です。title: '@'
次のようにスコープに追加することで、正しく機能させることができます。
myApp.directive('myDirective', function() {
return {
template: "<div>{{text}}</div>",
scope: {
text: "@myDirective",
title: '@' // <-- added
}
};
});
これにより、次の DOM が生成されます。
<div ng-controller="MyCtrl" class="ng-scope">
<span id="theSpan" my-directive="One!!" title="Two!!" class="ng-isolate-scope ng-scope">
<div class="ng-binding">One!!</div>
</span>
</div>
ディレクティブのスコープで属性を指定しなくても、要素の属性が保持されるようにディレクティブをコーディングするにはどうすればよいですか? (おそらく、より良い質問は、title
属性が評価されないのはなぜですか?)
これは、問題を示すjsFiddleです。