2014-06-23 76 views
0

目前,我有重複的代碼,我有下面的例子: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
  1. $scope.user.window.element試圖訪問命名$scope.user.windowelement財產。您需要改爲$scope.user.window[element]

  2. this引用已創建函數的作用域。例如,您可以傳遞一個新參數that

  3. that.element將必須重寫爲that[element],原因與#1中的相同。

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

嘗試

$scope.user.window[element] 

當你需要引用一個屬性作爲sttring,則必須使用無支架塔季翁。 此外,我懷疑'這'會引用你想要的。您可能需要將此方法綁定到該方法。