gpt4 book ai didi

javascript - 使用 ng-click 更改 ng-repeat 循环中的值

转载 作者:搜寻专家 更新时间:2023-11-01 05:00:06 25 4
gpt4 key购买 nike

我想在 ng-repeat 循环中使用函数更改项目的值。

例如,这是行不通的。

HTML

<ul class="unstyled">
<li ng-repeat="todo in todoList.todos">
<span>{{todo.name}}</span>
<button ng-click="example(todo)">Change me</button>
</li>
</ul>

JS

$scope.example = function(v) {
v.name = 'i am different now';
};

完整示例

http://plnkr.co/edit/kobMJCsj4bvk02sveGdG

最佳答案

当使用 controllerAs 模式时,您应该在从 Controller 函数访问任何变量时使用 controller 别名。但这应该绑定(bind)到 controllerthis 上下文。

<button ng-click="todoList.example(todo)">Click me</button>

Demo Here

扩展

在 Controller 工厂函数中使用 this 关键字时还要记住。您应该将 this 变量分配给某个变量,以确保您正在使用的 this 不是其他 this,请查看 this context related issue .

angular.module('todoApp', [])
.controller('TodoListController', function() {
var toList = this;
toList.todos = [{name:'test 1'},{name:'test 2'}];
toList.example = function(v) {
v.name = 'ora bene';
};
});

关于javascript - 使用 ng-click 更改 ng-repeat 循环中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35650518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com