简体   繁体   中英

AngularJS changing property name in model

The data I am receiving is structured like this. I am taking this data and displaying it on to a graph with radio buttons. Each radio button will show the "category name", but actually I need to show a different label for the category name other than what is coming back in the data. For example if the category name is false, I need the radio button to display: "Other" and if it is true I need to display: "Our Company".

0: Object
    categoryName: false
    categories: Array[4]
        0: Object
        1: Object
        2: Object
        3: Object
1: Object
    categoryName: true
    categories: Array[2]
        0: Object
        1: Object

<span ng-repeat="testCat in testCategories">
<input type="radio" name="programSelector2" ng-model="testCategoryId" ng-click="load( testCat.id )" value="{{testCat.id}}" >{{testCat.name}}
</span>

Need some help with controller logic I'm assuming to update the model based on what the categoryName is.

You can follow three different roads:

  • create a function to resolve the value
  • create an array to solve the value
  • use a condition in the expression

With resolve function:

$scope.resolve = function(key) {
    if (key == 'firstValue') {
        return 'First description';
    } else if (key == 'secondValue') {
        return 'Second description;
    }
}

and in the HTML

{{resolve(testCat.categoryName)}}  

With array

$scope.resolve = [];
$scope.resolve['firstValue'] = 'First description;
$scope.resolve['secondValue'] = 'Second description;

and in the HTML

{{resolve[testCat.categoryName]}}  

With conditional expression

Or in the case that categoryName has only true false values

 {{ testCat.categoryName ? 'First description' : 'Second description' }}

Create function in the controller like :

scope.getCategoryName=function(categoryName){
   if(categoryName === true)
     return 'Other';
   else 
   {
     ...
   }
}

and then call it from your html

<input type="radio" name="programSelector2" ng-model="testCategoryId" ng-click="load( testCat.id )" value="{{testCat.id}}" >{{getCategoryName(testCat.name)}}

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