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

时间:2014-06-23 15:27:51

标签: 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 (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')

2 个答案:

答案 0 :(得分:1)

  1. $scope.user.window.element尝试访问element名为$scope.user.window的媒体资源。您需要$scope.user.window[element]代替。

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

  3. that.element必须重写为that[element],原因与#1相同。

  4. 您无法为功能的参数指定新值(嗯,您可以,但它无法在功能范围之外访问)。更好地回报价值。

  5. 所以:

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

答案 1 :(得分:0)

$scope.user.window[element]

如果需要将属性作为sttring引用,则必须使用括号表示法。 另外,我怀疑“这个”会引用你想要的东西。你可能需要angular.bind这个方法。