antonyboom antonyboom - 3 months ago 7
AngularJS Question

How to assign key from one variable to value in another, angular

I'm rendering form on a page with help ng-repeat, data for this form comes dynamically from request. In this data I have nested array - categories. Inside of this array defined ids and list of this ids I can see in my form. From another request I get another array where defined names for ids. How can I assign key value from one variable to key value from another variable that display on the page list of names instead of list of ids

This is plunker with my problem. I appreciate any help, thanks in advance.

html of my form

<form style="padding: 15px" ng-submit="submitForm(rowData)">
<div class="form-group row">
<div ng-repeat="(key, value) in rowData">
<div ng-if="key | id">
<label class="col-sm-6">{{key | makeUppercase}}</label>
<div class=" col-sm-6">
<input class="form-control rowValue"
id="rowData[key]"
ng-if="!isObject(value)"
type="text"
ng-model="rowData[key]"
/>
<span
class="form-control rowValue"
id="categories"
ng-if="isObject(value) && key == 'categories'"
ng-model="rowData.categories">
{{rowData.categories}}
</span>
</div>
</div>
</div>
</div>
<div class="pull-right">
<button type="submit" class="btn btn-default"
ng-if="rowData">Save</button>
<button type="button" class="btn btn-default" ng-if="rowData"
ng-click="cancelForm()">Cancel</button>
</div>
</form>

Answer

My implementation is very naive but it displays what you want. I add this function to your controller

  $scope.getCategoryIns = function(ids){
    var categoriesName = [];
    for (var j = 0; j < ids.length; j ++){
    id = ids[j];
   for(var i= 0; i < $scope.categories.length;i++)
   {
      if ( $scope.categories[i].id == id){
        categoriesName.push($scope.categories[i].name);
      }
   }
 }

  var str = categoriesName.join(', ');
  return str;
}

and in HTML use this function as following

<span class="form-control rowValue"  id="categories" ng-if="isObject(value) && key == 'categories'" ng-model="rowData.categories">
                       {{getCategoryIns(rowData.categories)}}</span>

plnkr here

Comments