我有一个带有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
评估属性?)