AngularJS指令 – 如何有条件地应用模板?
发布时间:2020-12-17 08:38:31 所属栏目:安全 来源:网络整理
导读: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="maybe
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:
function resolveTemplate(tElement,tAttrs) { } angular.module('MyApp').directive('maybeLink',function() { return { //... template: resolveTemplate,//... }; }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |