简体   繁体   中英

Angularjs - showing element based on a presence of id in array

Does anyoen know how to check (in the View) for a presence of id in a given array?

Lets say I have an array like so:

var arr = [123, 456, 789];

and a data source like this:

var data = [
  {id: 123, name: 'foo'},
  {id: 456, name: 'bar'},
  {id: 789, name: 'baz'}
];

Now in the view while iterating over the data array I would like to show/hide elements based on a presence of id in the arr like so:

<div ng-repeat="item in data">
    <span ng-show="item.id in arr"></span>
</div>

The above code item.i in arr of course does not work for obvious reasons. Anyone know how to achieve that functionality? Not to mention the ng-show block should always kick-in whenever the arr array is altered.

Thanks in advance.

You can just create a method in your scope

function MyCtrl( $scope ) {
  $scope.data = ...

  $scope.enabled = ...


  $scope.visible = function (id ) { 
    return $scope.enabled.indexOf(id) > -1
  } 

}

and

<span ng-show="visible(item.id)" ></span>

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