简体   繁体   English

在Angular.js中,如何在单击时使用ng-repeat迭代的对象列表中修改元素的属性?

[英]In Angular.js, how do I modify the properties of an element in a list of objects iterated over with ng-repeat on click?

In my controller I have an array of objects (I'm just getting started, so forgive me if this is terribly naive or something): 在我的控制器中,我有一个对象数组(我才刚刚开始,所以如果这太天真了,请原谅我):

$scope.links = [
    {
        'votes': 6,
        'voted_on': false
    },
    {
        'votes': 7,
        'voted_on': false
    }
];

I want to list these out in the view and modify some of the properties on click, maintaining some complex state reflecting the change in the DOM: 我想在视图中列出这些内容,并在单击时修改某些属性,以保持反映DOM中更改的某些复杂状态:

<ul>
    <li ng-repeat="link for links">
        <a ng-click="updateProperties()">Vote</a>
        {{link.votes}}
    </li>
</ul>

You know, I would like updateProperties() to manage a lot of stateful logic (change the color of the {{link.votes}} , increment link.votes , disallow incrementing if they have already voted, etc. ). 您知道的,我希望updateProperties()管理很多有状态的逻辑(更改{{link.votes}}的颜色,递增link.votes ,如果他们已经投票就禁止递增等)。 I get that I need to define the function on $scope but I'm just not sure what that would look like, so help would be much appreciated. 我知道我需要在$scope上定义函数,但是我不确定那是什么样子,因此非常感谢您的帮助。 Thanks. 谢谢。

One way would be to have updateProperties to have a parameter that is a unique identifier for the poll in which the vote is related to. 一种方法是让updateProperties具有一个参数,该参数是与投票相关的投票的唯一标识符。 The logic of dealing with what the click does will reside inside updateProperties and that will be up to you to define as per what you want. 处理点击行为的逻辑将驻留在updateProperties ,这取决于您是否要根据自己的需要进行定义。 The function is just a standard javascript function and can be defined inside your controller like 该函数只是一个标准的javascript函数,可以在您的控制器内部定义,例如

$scope.updateProperties = function(pollID){...} and as long as the controller that this resides in is active in the part of the page that you call it from then you can use the function. $scope.updateProperties = function(pollID){...} ,只要$scope.updateProperties = function(pollID){...}在的控制器在您调用它的页面部分中处于活动状态,就可以使用该功能。

Check out the Angular Docs , and their mockups on the main page (I think one that's on the main page might be of use to you). 在主页上查看Angular Docs及其模型(我认为主页上可能有用的一个文件)。

An easier way is to use the $index to find the item, as an example 例如,一种更简单的方法是使用$ index查找项目

<ul>
<li ng-repeat="link for links">
    <a ng-click="toggleVotedOn($index)">Vote</a>
    {{link.votes}}
</li>

And in your controller, 在您的控制器中

$scope.toggleVotedOn = function(i) {
    $scope.links[i].voted_on = !($scope.links[i].voted_on);
}

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

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