[英]How to add a new key:value pair to an already existing array state variable react native
[英]How to add new key/value pair element to an existing array?
var onHomePageLoaded = function(retMsg)
{
$scope.data = retMsg.data.records;
$scope.data.link : 'http://www.newwebsite.com'
}
將鏈接元素(鍵/值)添加到javascript對象后,我無法在HTML模板中獲得相同的內容
<div ng-repeat="record in data">
<a ng-href="{{record.link}}"> Click Here </a>
</div>
Javascript是一種動態語言。 您可以通過非常簡單的方法向現有對象添加屬性,例如為現有屬性分配值。 只需添加一個新屬性
$scope.data.link = 'http://www.newwebsite.com'
如果retMsg.data.records
是一個數組,仍然可以向$scope.data
添加一個屬性。
如果要為數組中的每個對象使用不同的鏈接,請執行此操作。
$scope.data.forEach(function(obj){
obj.link = "your custom link" // write your logic here to produce different link.
});
如果數據是數組,則可以使用
$scope.data.push(yourData);
例如
$scope.data.push({link : 'http://www.newwebsite.com'});
或者,如果要訪問數組內部的對象並為它們添加一個鍵值對,則可以執行以下操作:
// add the link to the first entry
$scope.data[0].link = 'http://www.newwebsite.com';
抱歉。 不知道我是否很好理解。
也許您可以將scope.data定義為:
$scope.data = {retMsg.data.records}
然后例如一個函數:
$scope.addNew = funtion(){
$scope.data.newElement = $scope.viewElement
};
在您的HTML中
<label>{{data}}</label> // Which makes reference to the $scope.data at the controller
<input ng-change="addNew()" ng-model="viewElement"></input>
<label>{{data.newElement}} // Will be empty at the very beginning but will show the new element once it is created.
希望能幫助到你
我發現您的代碼有幾個問題。
首先,在ng-repeat
使用變量名稱record
,然后在ng-href
使用report
。 我認為這些應該是相同的。
另外, link
不是record
的成員,而是data
的成員。 您可以在此處將其設置為data
成員: $scope.data.link : 'http://www.newwebsite.com'
。 如果要將鏈接添加到每個record
,請在onHomePageLoaded
函數中,遍歷添加到data
所有記錄,並將link
屬性添加到每個記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.