Javascript AngularJS设置函数以防止重复
目前,我有重复的代码,其中有以下示例:Javascript AngularJS设置函数以防止重复,javascript,angularjs,function,Javascript,Angularjs,Function,目前,我有重复的代码,其中有以下示例: if ($scope.user.window.title == 'true'){ if (this.title){ title = '<h2>'+this.title+'<h2>'; } else { title = ''; } } else { title = ''; } if ($scope.user.window.football == 'true'){
if ($scope.user.window.title == 'true'){
if (this.title){
title = '<h2>'+this.title+'<h2>';
} else {
title = '';
}
} else {
title = '';
}
if ($scope.user.window.football == 'true'){
if (this.football){
football = '<p>'+this.football+'<p>';
} else {
football = '';
}
} else {
football = '';
}
用法
CheckWindow('title','h2')
CheckWindow('football','p')
试试看
$scope.user.window[element]
当需要引用属性作为字符串时,必须使用括号表示法。
此外,我怀疑“这个”是否会引用您想要的内容。您可能需要将其绑定到方法
$scope.user.window.element
尝试访问$scope.user.window
的名为element
的属性。您需要$scope.user.window[element]
此
引用已创建函数的作用域。例如,您可以传递一个新参数,该参数为
that.element
必须重写为that[element]
,原因与#1中相同函数检查窗口(即,元素,标记){
if($scope.user.window[element]&&that[element]){
返回“”+该[元素]+“”;
}
返回“”;
}
title=CheckWindow(这是“title”、“h2”);
football=CheckWindow(这是'football','p');
$scope.user.window[element]
function CheckWindow(that, element, tag) {
if ($scope.user.window[element] && that[element]){
return '<'+tag+'>'+that[element]+'</'+tag+'>';
}
return '';
}
title = CheckWindow(this, 'title', 'h2');
football = CheckWindow(this, 'football', 'p');