选择特定键然后显示特定值而不用ng-repeat

时间:2016-03-20 05:35:33

标签: javascript angularjs

我正在使用angular,我正在尝试根据键显示键值对中的值。我已经看到使用ng-repeat的解决方案,但这看起来很混乱。有没有更好的解决方案不涉及控制器逻辑?

E.g。

说我在数组中有ID和名称的结果:

$scope.fruits = [
 {id:1, name:"apple"},
 {id:2, name:"banana"},
 {id:3, name:"cherry"}
];

$scope.fruit_selection = 3;

然后在我看来,我想看看

<a>{{some logic that shows cherry}}</a>

2 个答案:

答案 0 :(得分:1)

$scope.pickFruitById = function() {
    $scope.fruits.forEach(function(element){
    if(element.id == $scope.fruit_selection) {
        $scope.fruitToBeDisplayed  = element.name;
     } 
});
}
$scope.pickFruitById();

在HTML中:

<a>{{fruitToBeDisplayed}}</a>

pickFruitById是一个功能,可以选择ID为fruit_selection的水果并将其分配给$scope.fruitToBeDisplayed然后您可以使用{{}}表示法从HTML访问它

我将逻辑置于函数中的原因是,如果$scope.fruit_selection发生更改,则可以从HTML调用此函数以获取新的fruitToBeDisplayed

答案 1 :(得分:1)

查看demo,使用更少的代码/逻辑。

请找到以下代码:

HTML:

 <div ng-app="app" ng-controller="test">
    <span ng-repeat="item in fruits">
      <a ng-if="item.id == fruit_selection">
         {{item. name}}
      </a>
    </span>
 </div>

JS:

   var app = angular.module("app", []);

   app.controller ('test', function($scope) {
      $scope.fruits = [
         {id:1, name:"apple"},
         {id:2, name:"banana"},
         {id:3, name:"cherry"}
       ];
      $scope.fruit_selection = 3;
    });