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');