是否可以决定是否在AngularJS指令的链接功能中使用templateUrl
参数?
假设我有以下指令:
app.directive('sitesAndImprovements', function() {
return {
restrict: 'E',
replace:true,
templateUrl: '<path-to-file>/site-and-improvments.html',
link: function (scope, elem, attrs) {
scope.testClick = function() {
var myScope = scope;
//debugger;
}
scope.constructionCompleteClick = function () {
if (scope.construction_complete == 'Yes') {
scope.hold_back = '';
scope.percent_complete = 100;
} else
if (scope.construction_complete == 'No') {
scope.hold_back = '1';
if (scope.percent_complete == 100) {
scope.percent_complete = '';
}
}
}
scope.calcTotal = function () {
var total;
total = (scope.main || 0) + (scope.second || 0) + (scope.third || 0) + (scope.fourth || 0);
scope.total = total || null;
}
}
}
})
我想控制是否使用templateUrl
以及replace
函数中的link()
参数。
这是因为我已经在大约10个地方使用templateUrl
实现了此指令,现在我想开始使用此功能,但我不想对现有和正在运行的代码进行更改。
这可能吗?如何?
塔雷克
答案 0 :(得分:0)
我认为你不能在link
中做到这一点,但我相信你可以将templateUrl
变成一个可以为指令返回不同值的函数。
尝试为templateUrl
templateUrl: function() {
if (someCondition) {
return '<path-to-file>/site-and-improvments.html';
} else {
return null;
}
},
答案 1 :(得分:0)
app.directive('sitesAndImprovements', function() {
return {
restrict: 'E',
replace:function(){
if (aCondition){
return true;
} else {
return false;
}
},
templateUrl: function(){
if (aCondition){
return '<path-to-file>/site-and-improvments.html';
} else {
return undefined;
}
},
link: function (scope, elem, attrs) {
scope.testClick = function() {
var myScope = scope;
//debugger;
}
scope.constructionCompleteClick = function () {
if (scope.construction_complete == 'Yes') {
scope.hold_back = '';
scope.percent_complete = 100;
} else
if (scope.construction_complete == 'No') {
scope.hold_back = '1';
if (scope.percent_complete == 100) {
scope.percent_complete = '';
}
}
}
scope.calcTotal = function () {
var total;
total = (scope.main || 0) + (scope.second || 0) + (scope.third || 0) + (scope.fourth || 0);
scope.total = total || null;
}
}
}
})
说明:如the source code所述,只有在templateUrl
给出时才会编译模板:
...
if (directive.templateUrl) {
hasTemplate = true;
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
if (directive.replace) {
replaceDirective = directive;
}
// eslint-disable-next-line no-func-assign
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
...
请注意,aCondition
可以是传递给指令的属性,以启用/禁用templateUrl和replace。另请注意replace
is deprecated。