简体   繁体   中英

angularjs ng-repeat key value pair with combined conditions

I want to do a "ng-repeat" with some particular condition on the key value pairs. My json data is like:

mylist = {
  "Tom Hans": true,
  "Carl King": true,
  "anotherfield": "Josef Bush"
}

Or:

mylist = {
  "Tom Hans": true,
  "Carl King": true,
  "anotherfield": ""
}

two of my keys are some string format as above and their values are always "true", and there is another fixed key "anotherfield" which can have either an empty value or have some value like above.

<ul>
    <li ng-repeat="(key, val) in mylist" ng-if="val == true">
        {{key}}</li>
</ul>

here is the desired result: the output for the first version of the variable:

Tom Hans
Carl King
Josef Bush

the output for the second version of the variable when the "anotherfield" is empty:

Tom Hans
Carl King

could somebody help me achieve this?

<ul>
    <li ng-repeat="(key, val) in mylist" ng-if="val || val.length">
        {{ val.length ? val : key }}</li>
</ul>

val || val.length val || val.length will match if val is true, or if its length is >0.

If the val has a length, it will display the val, otherwise the key.

This seems to be simple yet explicit:

<ul>
    <li ng-repeat="(key, val) in mylist" ng-if="val">
        {{ val === true ? key : val }}
    </li>
</ul>

Personally I would map this to array in controller which will cut down watchers and child scopes in view and simplify view .

$scope.objToArray = function(obj){      
  return Object.keys(obj).reduce(function(a, key){
     if(obj[key] === true){
       a.push(key)
     }else if(typeof obj[key] === 'string' && obj[key].trim().length){
       a.push(obj[key])
     }
     return a;
  },[]);      
}

View

<li ng-repeat="item in objToArray(mylist)">
  {{item}}
</li>

Plunker demo


Ideally however if you control data structure at source I would consider creating more friendly structure

You don't need to ask if value == true in an if statement, if the value is true, just use it, on the other hand, the value if is not "", may have a length, so, in hava script, if something is >0, is true, finally you can do an ng-switch-when:

<ul>
    <li ng-repeat="(key, val) in mylist" ng-switch="val">
    <li ng-switch-when="val"> {{key}}</li>
    <li ng-switch-when="val.length"> {{val}}</li>

</ul>

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