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(一次只能看到一个).
我怎么能重写这个指令,它会添加< span>或者< a>到DOM,但不是两个?
UPDATE
好吧,我想我可以使用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>,但双向数据绑定也不起作用.我真的很想知道如何修复双向数据绑定问题.有任何想法吗?
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:
原文链接:https://www.f2er.com/angularjs/143873.htmlYou 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,//... }; });