AngularJS在模型中更改属性名称

时间:2016-01-28 16:46:21

标签: javascript arrays angularjs datamodel

我收到的数据结构如下。我正在获取这些数据并将其显示在带有单选按钮的图形上。每个单选按钮都会显示"类别名称",但实际上我需要为类别名称显示不同的标签,而不是数据中的内容。例如,如果类别名称为false,我需要单选按钮来显示:"其他"如果确实如此,我需要展示:"我们的公司"。

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>

需要一些控制器逻辑方面的帮助我假设根据categoryName是什么来更新模型。

2 个答案:

答案 0 :(得分:1)

您可以遵循三条不同的道路:

  • 创建一个解析值的函数
  • 创建一个数组来解决值
  • 在表达式中使用条件

使用解析功能:

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

并在HTML中

{{resolve(testCat.categoryName)}}  

使用数组

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

并在HTML中

{{resolve[testCat.categoryName]}}  

使用条件表达式

或者categoryName只有真假值的情况

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

答案 1 :(得分:0)

在控制器中创建函数,如:

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

然后从你的HTML

中调用它
<input type="radio" name="programSelector2" ng-model="testCategoryId" ng-click="load( testCat.id )" value="{{testCat.id}}" >{{getCategoryName(testCat.name)}}
相关问题