Javascript 在角度指令中有条件地加载模板
我试图仅有条件地加载指令模板,例如-Javascript 在角度指令中有条件地加载模板,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我试图仅有条件地加载指令模板,例如- .directive('truncate',["$window", function($window, $compile){ return { restrict: 'A', templateUrl: 'template/truncate.html', link: function (scope, element, attrs) { var height = element[0].offsetHeig
.directive('truncate',["$window", function($window, $compile){
return {
restrict: 'A',
templateUrl: 'template/truncate.html',
link: function (scope, element, attrs) {
var height = element[0].offsetHeight;
var shouldBetruncated = height>200;
if(shouldBetruncated){
// want my template to load here, otherwise template is not loaded
};
}
}
}])
.run(function ($templateCache) {
$templateCache.put('template/truncate.html',
'template code'
);
})
有什么办法可以做到这一点吗
/*This will solve you problem*/
link: ...
templateUrl: function() {
if(shouldBetruncated) {
return 'template/truncate.html';
} else {
return '';
}
}
有关更多信息,您可以从html传递模板或根据条件生成模板
有关更多信息,您可以通过html传递模板或根据条件生成模板
.directive('truncate',["$window", function($window, $compile){
return {
restrict: 'A',
templateUrl: 'template/truncate.html',
link: function (scope, element, attrs) {
var height = element[0].offsetHeight;
shouldBetruncated = height>200;
if(shouldBetruncated){
loadTemplate();
};
// function loadTemplate -- begins
var loadTemplate = function ($templateCache) {
$templateCache.put('template/truncate.html',
'template code'
);
};
// -- ends
}
}
}]); 试试这个
.directive('truncate',["$window", function($window, $compile){
return {
restrict: 'A',
templateUrl: 'template/truncate.html',
link: function (scope, element, attrs) {
var height = element[0].offsetHeight;
shouldBetruncated = height>200;
if(shouldBetruncated){
loadTemplate();
};
// function loadTemplate -- begins
var loadTemplate = function ($templateCache) {
$templateCache.put('template/truncate.html',
'template code'
);
};
// -- ends
}
}
}]); 为什么需要?为什么需要?在loadTemplate函数运行之前,指令无法找到模板,因此它会引发错误。您可以创建一个plunkr链接,以便有助于解决问题。在loadTemplate函数运行之前,指令无法找到模板,因此它会抛出一个错误。你能创建一个plunkr链接吗,这样对解决问题很有帮助。templateUrl:“template/truncate.html”,这是一种对象语法,你确定可以在这里使用它,因为它不起作用吗?如果条件应该在链接函数之外,但问题是我的条件将仅在链接函数中计算,所以需要从那里应用这个,我已经根据您的要求更新了答案,只要检查一下我不清楚,应该如何在链接函数外运行定位变量,或者可能我正在阅读错误的代码templateURL:'template/truncate.html',这是一个对象语法,你确定它可以在这里使用,因为它不工作,如果条件应该在链接函数之外,但问题是我的条件将只在链接函数中进行评估,因此需要从那里应用它。我已经根据你的要求更新了答案,如果我不清楚,请检查它,在link函数之外应该如何使用betruncated变量,或者可能我读错了代码