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,但不是两者兼而有之?更新
好的,我想我可以使用
ng-if
像那样: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>
,但双向数据绑定(bind)也不起作用。我真的很想知道如何解决双向数据绑定(bind)问题。有任何想法吗?DEMO
angular.module('MyApp').directive('maybeLink', function($compile) {
return {
scope: {
maybeLink: '=',
maybeLinkText: '='
},
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));
}
}
};
});
最佳答案
我认为这是基于范围属性注入(inject)动态模板的最简洁方法
angular.module('app')
.directive('dynamic-template', function () {
return {
template:'<ng-include src="template"/>',
restrict: 'E',
link: function postLink(scope) {
scope.template = 'views/dynamic-'+scope.type+'.html';
}
};
})
关于angularjs - 如何通过自定义 Angular 指令有条件地应用模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18892793/