[英]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'
}
After i have added link element (key/value) to the javascript object, i am not able to get the same in the HTML template 将链接元素(键/值)添加到javascript对象后,我无法在HTML模板中获得相同的内容
<div ng-repeat="record in data">
<a ng-href="{{record.link}}"> Click Here </a>
</div>
Javascript is a dynamic language. Javascript是一种动态语言。 You can add properties to existing objects in a very simple way , like assigning a value to an existing property.
您可以通过非常简单的方法向现有对象添加属性,例如为现有属性分配值。 Just add a new property
只需添加一个新属性
$scope.data.link = 'http://www.newwebsite.com'
if retMsg.data.records
is an array, still you can add a property to $scope.data
. 如果
retMsg.data.records
是一个数组,仍然可以向$scope.data
添加一个属性。
if you want different link for every object in array then, do this. 如果要为数组中的每个对象使用不同的链接,请执行此操作。
$scope.data.forEach(function(obj){
obj.link = "your custom link" // write your logic here to produce different link.
});
If data is an array you can use 如果数据是数组,则可以使用
$scope.data.push(yourData);
for example 例如
$scope.data.push({link : 'http://www.newwebsite.com'});
Or if you want to access the objects inside the array and add them a key value pair you can do as follow: 或者,如果要访问数组内部的对象并为它们添加一个键值对,则可以执行以下操作:
// add the link to the first entry
$scope.data[0].link = 'http://www.newwebsite.com';
Sorry. 抱歉。 Do not know if I understood well.
不知道我是否很好理解。
Maybe you can define scope.data as: 也许您可以将scope.data定义为:
$scope.data = {retMsg.data.records}
Then for example a function: 然后例如一个函数:
$scope.addNew = funtion(){
$scope.data.newElement = $scope.viewElement
};
In your HTML 在您的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.
Hope it helps 希望能帮助到你
I see several issues with your code. 我发现您的代码有几个问题。
First, you use the variable name record
in your ng-repeat
, but then use report
in ng-href
. 首先,在
ng-repeat
使用变量名称record
,然后在ng-href
使用report
。 I assume those should be the same. 我认为这些应该是相同的。
Also, link
isn't a member of record
, it is a member of data
. 另外,
link
不是record
的成员,而是data
的成员。 You set it as a member of data
here: $scope.data.link : 'http://www.newwebsite.com'
. 您可以在此处将其设置为
data
成员: $scope.data.link : 'http://www.newwebsite.com'
。 If you want to add that link to each record
, in your onHomePageLoaded
function, you'll need to loop through all the records you add to data
, and add the link
property to each one. 如果要将链接添加到每个
record
,请在onHomePageLoaded
函数中,遍历添加到data
所有记录,并将link
属性添加到每个记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.