简体   繁体   中英

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

<div ng-repeat="record in data">

  <a ng-href="{{record.link}}"> Click Here </a>

</div>

Javascript is a dynamic language. 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 .

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 = {retMsg.data.records}

Then for example a function:

    $scope.addNew = funtion(){
     $scope.data.newElement = $scope.viewElement
    };

In your 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 . I assume those should be the same.

Also, link isn't a member of record , it is a member of data . You set it as a member of data here: $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM