2017-01-31 64 views
0

在組件中使用屬性綁定時,傳遞給控制器​​的數據始終是一個字符串。然而,我試圖傳遞一個整數,並且無法將其從字符串轉換爲轉換棒。將整數綁定到AngularJS 1.5組件

我試過將數據保存爲$onInit()中的一個整數,但在此函數之外,數據返回到其原始狀態(類型和值)。我知道組件不應該修改作爲一般規則傳入的數據,但由於這是一個屬性綁定,並且數據是按值傳遞的,所以我認爲這並不適用。

function IntegerBindingController() { 
    this.$onInit = function() { 
    // Assuming 'number="2"' in the HTML 
    // This only changes the data inside this function 
    this.number = parseInt(this.number) 
    this.typeofNumber = typeof this.number // evaluates to 'number' 
    this.simpleAdd = this.number + 5 // evaluates to 7 
    this.dataAdd = this.numberOneWay + 5 
    console.log(this) 
    } 

    this.test = function() { 
    // this.number is a string inside this function 
    this.typeofNumber = typeof this.number // evaluates to 'string' 
    this.simpleAdd = this.number + 5 // evaluates to 25 
    } 
} 

我可以將數據複製到控制器上的一個新的屬性解決這個問題,但我很好奇,如果有人可以解釋這裏發生了什麼。請參閱此Plunker以瞭解該問題的一個工作示例。

回答

0

解決方案我最終走向機智h將使用$onChanges來處理綁定的數據值。在我的情況下,至少有一個值可能會在父組件中的異步調用後發生更改,因此整體上這是有意義的。正如Prinay Panday注意到的那樣,@綁定總是以字符串形式出現。 $onInit()方法保證綁定可用,但不能保證它們會改變,所以即使您更改了組件上的值,Angular也可以稍後更改它。這是文檔建議將綁定值複製到本地變量的另一個原因,如果您需要操縱它們。至於$onChanges()溶液,它是這樣的

function IntegerBindingController() { 
    this.$onChanges(changes) { 
    if (changes.number && changes.number.currentValue) { 
     this.number = parseInt(changes.number.currentValue) 
    } 
    } 

    this.test = function() { 
    this.typeofNumber = typeof this.number // evaluates to 'number' 
    this.simpleAdd = this.number + 5 // evaluates to 7 (assuming this.number was 2) 
    } 
} 
3

傳遞數字'@'將始終將其作爲字符串傳遞。如果您希望在組件綁定中使用「=」的對象值傳遞號。

所以:

var IntegerBindingComponent = { 
    controller: IntegerBindingController, 
    bindings: { 
    string: '@', 
    number: '=', 
    numberOneWay: '<' 
}, 
template: _template 
} 

一個體面的解釋可以在這裏找到:http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/

或在這裏:Need some examples of binding attributes in custom AngularJS tags

「在 '=' 符號基本上提供了一種機制傳遞對象到您的它始終將此從指令的父範圍中拉出來......「

+0

我想部件VS指令的要點之一是使用單向綁定('<'),而不是雙向('=' )?在任何情況下,使用'<'都行,但問題仍然是爲什麼在'$ onInit()'中修改'this.number'只會在該函數的作用域內生效。另外,目標是能夠通過模板傳遞一個整數,而不必先創建一個對象。 –