angularjs – 如何通过自定义Angular指令有条件地应用模板?
发布时间:2020-12-17 08:01:24 所属栏目:安全 来源:网络整理
导读: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="may
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>,但双向数据绑定也不起作用.我真的很想知道如何修复双向数据绑定问题.有任何想法吗? 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:
function resolveTemplate(tElement,tAttrs) { } angular.module('MyApp').directive('maybeLink',function() { return { //... template: resolveTemplate,//... }; }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |