如何将选定的对象属性名称输出到angularJs

时间:2017-08-21 10:10:46

标签: javascript html angularjs

我的maincontroller中有三个变量,一个用于选择人,一个用于与所选人名相关的流派,以及一个包含数据的对象数组。我在select元素环境中将数据绑定在一起,但现在我的目标是输出段落中的选定项目以进行进一步操作,我设法输出所选人员但它出现在垂直对齐中。有人可以告诉我如何输出例如在我的情况下让我们这样说,我选择克里斯并在我的段落中我想得到“克里斯听的流派是独立,鼓声,Dubstep和电子”

myApp.controller('mainController', function($scope){
  $scope.selectedPerson = 0;
  $scope.selectedGenre = null;
  $scope.people = [
    { id: 0, name: 'Leon', music: [ 'Rock', 'Metal', 'Dubstep', 'Electro' ] },
    { id: 1, name: 'Chris', music: [ 'Indie', 'Drumstep', 'Dubstep', 'Electro' ] },
    { id: 2, name: 'Harry', music: [ 'Rock', 'Metal', 'Thrash Metal', 'Heavy Metal' ] },
    { id: 3, name: 'Allyce', music: [ 'Pop', 'RnB', 'Hip Hop' ] }
  ];
});

HTML模板

<!DOCTYPE html>
<head>
    <title>Learning AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
    <script type="text/javascript" src='app.js'></script>
    <script type="text/javascript" src='maincontroller.js'></script>
</head>
<body>
    <div id='content' ng-app='myAng' ng-controller='mainController'>
        <select ng-model='selectedPerson' ng-options='list.name for list in people'></select>
        <select ng-model='selectedGenre'>
            <option ng-repeat='genre in people[selectedPerson.id].music'>{{genre}}</option>
        </select>
        <p ng-model='people' ng-repeat='person in people[selectedPerson.id].name'>{{person}}</p>
    </div>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

  

我设法输出选定的人,但它出现在垂直对齐中。

您在单个String上运行ng-repeat指令。这就是你得到类似内容的原因:

C

h

r

i

s

可能是这样的:

<p>Genre that {{people[selectedPerson.id].name}} listen are  {{people[selectedPerson.id].music.join(', ')}}<p>

Demo

      <select ng-model='selectedPerson' ng-options='list as list.name  for list in people'>
        <option value="">-- Select Person --</option>
      </select>


        <select ng-model='selectedGenre'>
            <option ng-repeat='genre in people[selectedPerson.id].music'>{{genre}}</option>
        </select>


        <p>Genre that {{people[selectedPerson.id].name}} listen are  {{people[selectedPerson.id].music.join(', ')}}<p>