AngularJS设置了一个功能来防止重复



目前我有重复的代码,其中有以下示例:

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 = '';
}

我尝试了以下方法,但没有成功,它说$scope.user.window.football$scope.user.window.title不存在。我认为这是由于下面的函数将值作为$scope的字符串发送。

function CheckWindow(element,tag) {
    console.log(element);
    if ($scope.user.window.element == 'true'){
        if (this.element){
            element = '<'+tag+'>'+this.element+'</'+tag+'>';
        } else {
            element = '';
        }
    } else {
        element = '';
    }
}

用法

CheckWindow('title','h2')

CheckWindow('football','p')

  1. $scope.user.window.element尝试访问$scope.user.window的名为element的属性。您需要$scope.user.window[element]

  2. this是指创建的函数的范围。例如,您可以传递一个新的参数that

  3. 由于与#1中相同的原因,that.element将不得不被重写为that[element]

  4. 不能为函数的参数指定新值(当然可以,但在函数的作用域之外无法访问(。更好的回报价值。

因此:

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

尝试

$scope.user.window[element]

当您需要将属性引用为字符串时,必须使用括号表示法。此外,我怀疑"this"是否会引用您想要的内容。您可能需要将其与方法进行角度绑定。

最新更新