简体   繁体   English

使用angularjs在点击时更新页面的一部分

[英]Update part of page on click with angularjs

I'm new to angular. 我是新手。 If this is a duplicate, please post a link. 如果重复,请发布链接。

Ok, so I in javascript I have a list of items, lets say this: 好的,所以我在javascript中有一个项目列表,可以这样说:

[{
    name: 'Bob',
    age: 24,
},
{
    name: 'Smith',
    age: 56,
},
{
    name: 'Lisa',
    age: 12,
}]

All the name properties are printed out in a list at the left of the page, like this: 所有name属性都打印在页面左侧的列表中,如下所示:

<li data-ng-repeat="person in persons">{{tournament.name}}</li>

All this works, but here is the thing. 所有这些都有效,但这就是问题。 When I click a person in the list, I want to display more detailed information to the right of the list about that person. 当我单击列表中的某个人时,我想在列表右侧显示有关该人的更多详细信息。

If I click on Bob in the list, it should display both name and age to the right of the list. 如果我单击列表中的Bob ,它将在列表右侧显示nameage

I can't figure this out in angular. 我无法确定这一点。 Can anyone explain how I update a part of the page with that information? 谁能解释我如何使用该信息更新页面的一部分?

You can do that with a simple click on your li like that : 您可以这样简单地单击您的li来做到这一点:

<ul data-ng-repeat="person in persons">
  <li ng-click="detail($index)">{{person.name}}</li>
</ul>

The $index is the index of the ng-repeat really useful to mange with arrays ! $ index是ng-repeat的索引,对数组管理非常有用!

You add a div where you want to see the person details : 您在要查看人员详细信息的位置添加div:

  <div>
    {{personDetail.name}} {{personDetail.age}} 
  </div>

In your controller implement the detail function like that : 在您的控制器中实现如下的detail函数:

var app = angular.module('MyApp', []);

app.controller('MyCtrl', function($scope){

  $scope.persons = [{
                       name: 'Bob',
                       age: 24,
                    },
                    {
                       name: 'Smith',
                       age: 56,
                    },
                    {
                       name: 'Lisa',
                       age: 12,
                    }];

  $scope.detail = function(index){
      $scope.personDetail = $scope.persons[index];
  };

});

And voila ! 瞧!

working plnkr here : http://plnkr.co/edit/Wg4UD6?p=preview 在这里工作plnkr: http ://plnkr.co/edit/Wg4UD6?p=preview

<!-- left -->
<li data-ng-repeat="person in persons" ng-click="obj.selected=$index">
    {{person.name}}
</li>

<!-- right -->
<div>
    {{persons[obj.selected]["name"]}}
    {{persons[obj.selected]["age"]}}
</div>

Controller: 控制器:

$scope.obj = {
    selected:-1
};

HTML 的HTML

 <li data-ng-repeat="person in persons" ng-click="clicked(person)">

controller 控制者

 $scope.selectedNode = "";
 ...
 $scope.clicked = function(info) {
    $scope.selectedNode = info;
};

now create right side: 现在创建右侧:

<div>
  <pre>{{selectedNode | json}}</pre>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM