如何通过自定义 Angular 指令有条件地应用模板? [英] How to conditionally apply a template via custom Angular directives?
问题描述
考虑以下指令:
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>');
}
};
});
The directive adds both the <span>
and the <a>
to the DOM (only one is visible at a time).
How could I rewrite the directive such that it will add either <span>
or <a>
to the DOM, but not both?
更新
好的,我想我可以像这样使用 ng-if
:
OK, I guess I could use ng-if
like that:
template: '<span>' +
' <span ng-if="!maybeLink" ng-bind-html="text"></span>' +
' <a ng-if="maybeLink" href="#" ng-bind-html="text"></a>' +
'</span>'
但是,在这种情况下,如何摆脱周围的?
But, how could one get rid of the surrounding <span>
in this case?
更新 2
这是使用 $compile
的指令版本.它没有周围的 ,但双向数据绑定也不起作用.我真的很想知道如何解决双向数据绑定问题.有什么想法吗?
Here is a version of the directive that uses $compile
. It doesn't have the surrounding <span>
, but the two way data binding doesn't work either. I'm really interested to know how to fix the two way data binding issue. Any ideas?
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));
}
}
};
});
推荐答案
您或许可以使用 template
function.根据docs:
You might be able to use a template
function. According to the docs:
您可以将模板指定为表示模板的字符串,也可以指定为带有两个参数 tElement 和 tAttrs(在下面的编译函数 api 中描述)并返回表示模板的字符串值的函数.
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,
//...
};
});
这篇关于如何通过自定义 Angular 指令有条件地应用模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!