Search code examples
javascriptjqueryangularjsangular-directive

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>

Solution

  • 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.
    });