【问题标题】:How to solve the closure issue in angularjs如何解决angularjs中的闭包问题
【发布时间】:2014-11-04 07:43:42
【问题描述】:

我在 angularjs 中有一个示例 todo 应用程序。我的待办事项列表是一个数组。但每次只有数组项的最后一个值被添加到 li 中。

我已经在 jsbin 上复制了这个问题。

http://jsbin.com/simafuzidi/3/edit

我希望待办事项列表包含在文本框中键入的所有字段,而不仅仅是最后一个。我知道这是一个关闭问题,但我不确定在当前情况下如何解决。

谢谢

$scope.addTodo = function() {
  $scope.todos.push({text:$scope.todoText1,text:$scope.todoText2,text:$scope.todoText3,text:$scope.todoText4,done:false});
  $scope.todoText1 = '';
  $scope.todoText2 = '';
  $scope.todoText3 = '';
  $scope.todoText4 = '';
};




<form ng-submit="addTodo()">
        <input type="text" ng-model="todoText1"  size="30"
               placeholder="add new todo here1"><br />
        <input type="text" ng-model="todoText2"  size="30"
               placeholder="add new todo here2"><br />
        <input type="text" ng-model="todoText3"  size="30"
               placeholder="add new todo here3"><br />
         <input type="text" ng-model="todoText4"  size="30"
               placeholder="add new todo here4"><br />
         <input class="btn-primary" type="submit" value="add">
      </form>

【问题讨论】:

  • @Satpal:我放了一部分代码,但你最好看看实际问题。

标签: javascript jquery angularjs closures


【解决方案1】:

您应该在JSBIN 中看到控制台错误并通过Does JSON syntax allow duplicate keys in an object?

第 8 行:重复键“文本”。

代码

$scope.todos = [
  {todoText1:'learn angular', 
   done:true
  },
  {
    todoText1:'build an angular app', done:false
  }];
$scope.addTodo = function() {
  $scope.todos.push(
    {
      todoText1:$scope.todoText1,
      todoText2:$scope.todoText2,
      todoText3:$scope.todoText3,
      todoText4:$scope.todoText4,
     done:false
    });
  $scope.todoText1 = '';
  $scope.todoText2 = '';
  $scope.todoText3 = '';
  $scope.todoText4 = '';
};

HTML

  <ul class="unstyled">
    <li ng-repeat="todo in todos">
      <input type="checkbox" ng-model="todo.done">
      <span class="done-{{todo.done}}">{{todo.todoText1}} {{todo.todoText2}} {{todo.todoText3}} {{todo.todoText4}}</span>
    </li>
  </ul>

DEMO

【讨论】:

  • 谢谢,但这不仅仅是如何解决问题,问题是关闭在哪里发挥作用。
  • 不要建议将字符串连接作为具有多个键的对象的替代方案-.-
  • 不,不是。这是删除重复键的一种骇人听闻/无用的方法。我相信你能想到比字符串连接更好的选择。
  • @Cerbrus,更新答案
【解决方案2】:

我相信你的推送声明应该是这样的。

  $scope.todos.push({text:$scope.todoText1,done:false},{text:$scope.todoText2,done:false},{text:$scope.todoText3,done:false},{text:$scope.todoText4,done:false});

如果要推送所有项目。

【讨论】:

  • 这将创建4个待办事项,我只想做一项,而且我想了解闭包如何在angularjs中解决这个问题
  • @Cerbrus:你是在告诉我这不是关闭问题吗jsbin.com/simafuzidi/3/edit
猜你喜欢
  • 2011-09-09
  • 2011-05-05
  • 1970-01-01
  • 2020-05-13
  • 2020-10-29
  • 2021-06-12
  • 2021-11-05
  • 1970-01-01
相关资源
最近更新 更多