DEMO
考虑以下指令:
angular.module('MyApp').directive('maybeLink',function() {
return {
replace: true,scope: {
maybeLink: '=',maybeLinkText: '='
},template: '<span>' +
' <span ng-hide="maybeLink" ng-bind-html="text"></span>' +
' <a ng-show="maybeLink" href="#" ng-bind-html="text"></a>' +
'</span>',controller: function($scope) {
$scope.text = $scope.maybeLinkText.replace(/\n/g,'<br>');
}
};
});
该指令会将< span>和< a>到DOM(每次只有一个可见)。
如何重写指令,使其将添加 到DOM,但不是两者? >或
更新
OK,我想我可以使用ng-如果这样:
template: '<span>' +
' <span ng-if="!maybeLink" ng-bind-html="text"></span>' +
' <a ng-if="maybeLink" href="#" ng-bind-html="text"></a>' +
'</span>'
但是,如何摆脱周围的< span>在这种情况下?
更新2
这里是使用$ compile的指令的版本。它没有周围的< span>,但双向数据绑定也不工作。我真的很感兴趣,知道如何解决双向数据绑定问题。有任何想法吗?
DEMO
angular.module('MyApp').directive('maybeLink',function($compile) {
return {
scope: {
maybeLink: '=',link: function(scope,element,attrs) {
scope.text = scope.maybeLinkText.replace(/\n/g,'<br>');
if (scope.maybeLink) {
element.replaceWith($compile('<a href="#" ng-bind-html="text"></a>')(scope));
} else {
element.replaceWith($compile('<span ng-bind-html="text"></span>')(scope));
}
}
};
});
您可以使用模板函数。根据
docs:
You can specify template as a string representing the template or as a function which takes two arguments tElement and tAttrs (described in the compile function api below) and returns a string value representing the template.
function resolveTemplate(tElement,tAttrs) {
}
angular.module('MyApp').directive('maybeLink',function() {
return {
//...
template: resolveTemplate,//...
};
});