dynamic attribute reference inside angular ng-repe

2019-09-11 19:21发布

I build a dropdown directive, and it work with a different objects types, each object has own particular atributes, i need to get some particular field inside a ng-repat of my dropdown, now, it's fixed cityName, how i can change cityName for a variable, which stay on controller?

  <div class="listCombo" ng-show="showDrop" ng-mouseleave="lostFocus()">
        <table>
            <tr ng-repeat="result in results" ng-click="selectItem(result)">
                <td> {{result.cityName}} </td>
            </tr>
        </table>
    </div>

For example, i need to get peopleName rather than cityName.

2条回答
地球回转人心会变
2楼-- · 2019-09-11 19:44

Yes it is possible to change the property attribute dynamically in ng-repeat.Below is a sample example code on how to achieve this.

1) You should have data source like below to make things easy

$scope.objectsList = [{
                'name': 'Vikram',
                'Age': '25',
                'sex': 'M'
            }, {
                'name': 'Quantum',
                'Age': '26',
                'sex': 'F'
            }, {
                'name': 'Katty',
                'Age': '22',
                'sex': 'F'
            }];
            $scope.objName = 'name';

2) In your HTML have something like this in your ng-repeat

<p ng-repeat="obj in objectsList">
    {{obj[objName]}} <!-- here by changing the 'objName' we can decide which property value to be displayed dynamically-->

</p>
<input type="text" ng-model="objName"/><!-- This is for example..u dont need this-->

If you look at JS we have mentioned $scope.objName = 'name'; i.e it will display all the names in a list,if we change the $scope.objName to 'Age' then it will display corresponding ages in the data source.

Hope this is answers your question.

查看更多
萌系小妹纸
3楼-- · 2019-09-11 19:49

If you want to show cityName or peopleName conditionally in td,

you can use like this.

It's not building DOM conditionally but you can see like that. Wheather it is not a good way on you, but I hope it to help you.

 <div class="listCombo" ng-show="showDrop" ng-mouseleave="lostFocus()">
        <table>
            <tr ng-repeat="result in results" ng-click="selectItem(result)">
                <td ng-show="someCondition(result) === true"> {{result.cityName}} </td>
                <td ng-show="someCondition(result) === false"> {{result.cityName}} </td>
            </tr>
        </table>
    </div>
查看更多
登录 后发表回答