Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 选择特定键,然后不重复显示特定值_Javascript_Angularjs - Fatal编程技术网

Javascript 选择特定键,然后不重复显示特定值

Javascript 选择特定键,然后不重复显示特定值,javascript,angularjs,Javascript,Angularjs,我使用angular,我试图显示一个基于键的键值对中的值。我见过使用ng repeat解决这个问题的方法,但这看起来很混乱。有没有更好的解决方案不涉及控制器逻辑 例如 假设我在数组中有ID和名称的水果: $scope.fruits = [ {id:1, name:"apple"}, {id:2, name:"banana"}, {id:3, name:"cherry"} ]; $scope.fruit_selection = 3; 那么在我看来我想看看 <a>{{some

我使用angular,我试图显示一个基于键的键值对中的值。我见过使用ng repeat解决这个问题的方法,但这看起来很混乱。有没有更好的解决方案不涉及控制器逻辑

例如

假设我在数组中有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>
{{一些显示cherry的逻辑}
在HTML中:

<a>{{fruitToBeDisplayed}}</a>
{{fruitToBeDisplayed}
PickFroothById
是一个函数,它将拾取id为
Frooth\u selection
的水果,并将其分配给
$scope。然后,可以使用
{}
符号从HTML访问它

我之所以将逻辑放在函数中,是因为如果
$scope.fruit\u选择
发生了变化,那么您可以从HTML调用此函数,以获得新的
fruitToBeDisplayed

以较少的代码/逻辑查看

请查找以下代码:

HTML:


为什么不能直接使用水果选择索引访问水果?我对javascript还不太熟悉。你能举个例子吗?
水果[水果选择-1]。名称
这将显示“樱桃”。这就是你想要的吗?我用1,2,3作为例子,但它可以是任何水果的任何数字,如6,4,99等。你想展示哪种水果?全部还是一个?这似乎工作得很好,不过如果可能的话,我将尝试一个使用角度指令的版本。
<a>{{fruitToBeDisplayed}}</a>
 <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>
   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;
    });