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

标签 javascript angularjs angularjs-controller angularjs-controlleras

我想在 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/

相关文章:

javascript - 将 Ctrl 中的 switch 语句减少为禁用输入字段(AngularJS)

javascript - Backbone.js 和本地存储。必须指定 "url"属性或函数

javascript - 右键单击开放层中的特征向量(Javascript)

javascript - 通过输入字段中的天数更新日期选择器日期?

angularjs - AngularJS 指令模板可以呈现另一个指令吗?

javascript - 如何在 Windows Phone 上滚动 Bootstrap 模式

javascript - 将 Browserify 与 Angular JS 结合使用 - - 将服务传递到 Controller 中

javascript - 带有 ui-router 的 Angular 应用程序不会点击 Controller ,除非其内联函数

javascript - onBeforeRequest 重定向不起作用

javascript - AngularJS 使用 JS 从 API 设置 CSS 文件