javascript - 复选框 ng-click 触发了两次

标签 javascript html angularjs checkbox

我正在尝试动态填充一些复选框并使用所选项目来过滤数据。

我的 HTML

<div class="form-group" ng-repeat="category in categories">
  <label class="checkbox" >
    <input type="checkbox" ng-model="selection.ids[category.code]" id="{{category.code}}" 
           ng-click="toggleSelection(category)"
           />
    {{category.description}}
  </label>
</div>
<div class="form-group">
  <button type="submit" ng-click="filterSubmit();" class="btn btn-default">
    <span class="glyphicon glyphicon-search"></span> Filter
  </button>
</div>

在我的 Controller 中,我使用了这个 javascript,与我见过的大多数其他示例没有什么不同。

$scope.toggleSelection = function (category) {
  var idx = $scope.selection.indexOf(category);
  console.log('start '+ idx);

  // is currently selected
  if (idx > -1) {
    $scope.selection.splice(idx, 1);
  }
  // is newly selected
  else {
    $scope.selection.push(category);
  }
};

可悲的是,我看到控制台记录了 两次,一次是 -1,一次是 0。 所以我最终没有选中复选框。

当我使用 grunt 构建应用程序并将其放置在网络服务器上时,它可以正常工作,但是当我使用 grunt serve 运行它时,它会不断调用 Controller 两次。

最佳答案

作为布赖恩 mentions in a comment :

How is your code compiled differently with grunt serve versus for production? From the fact that it's being called twice in one instance but not the other points to your code being included twice when it gets concatenated via grunt serve, but not when built for prod.

Grunt 在不同的环境中设置不同。解决这个问题,问题就解决了。

关于javascript - 复选框 ng-click 触发了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30262151/

相关文章:

javascript - 从 JavaScript/React.js 中的 setInterval 返回

javascript - 如果选中,则将类添加到单选按钮

javascript - 如何在 Electron 中使用primus

javascript - 使用 Node.js 重定向到页面时出现类型错误

javascript - 如何删除元素上的所有数据属性?

javascript - 在 Canvas 上绘制时图像尺寸放大

javascript - AngularJS $http HTML 解析器

javascript - 使用 AngularJS 获取元素而不引用文档

css - 如何通过重新格式化输出不断从 img 更改为 anchor 和 div 背景

javascript - AngularJS - 输入更改传入指令的外部指令值