javascript - 将复选框绑定(bind)到 Angular 模型数组

标签 javascript arrays angularjs checkbox

我想在angular中直接绑定(bind)一个复选框列表到一个数组,这样当复选框被选中时,它的值被推到数组上,当没有被选中时,它被弹出,这样数组就模型始终代表我想要的最终状态。以前,我是通过将复选框映射到数组索引,然后剥离 null 值来完成的 - 但我想尝试另一种方式。

我想停止直接绑定(bind)到模型,而是在更新复选框时运行一个函数,该函数处理将数据放入数组。

  1. 这种方法有什么问题吗?
  2. 从 Controller 更新模型时有什么必须注意的事项吗?

HTML( Angular )

<div ng-app="app" ng-controller="Ctrl">
    <span ng-repeat='option in options'>
        <label>{{option.value}}</label>
        <input type="checkbox"         
        ng-value="option.code"
     ng-checked="selected.indexOf(option.code) > -1"
        ng-click="toggleSelect(option.code)" />
        <br />
    </span><br />
    {{selected}}
</div>

JavaScript( Angular )

var App = angular.module('app', []);

App.controller('Ctrl', ['$scope', function($scope){
    $scope.options = [
        {value: "Jan", code: 1}, 
        {value: "Feb", code: 2}, 
        {value: "Mar", code:  3}, 
        {value: "Apr", code:  4}, 
        {value: "May", code:  5}, 
        {value: "Jun", code:  6}, 
        {value: "Jul", code:  7}, 
        {value: "Aug", code:  8}, 
        {value: "Sep", code:  9}, 
        {value: "Oct", code:  10}, 
        {value: "Nov", code:  11}, 
        {value: "Dec", code:  12}
    ];

    $scope.selected = [1, 2, 9]

    $scope.toggleSelect = function toggleSelect(code) {
        var index = $scope.selected.indexOf(code)

        if (index == -1) {
            $scope.selected.push(code)
        }
        else {
            $scope.selected.splice(index, 1)
        }
    }
}]);

演示:http://jsfiddle.net/rianodwyer/8dPRn/

最佳答案

I want stop binding directly to the model, but just run a function when the checkboxes are updated, which handles putting data on the array.

这是 Angular 的强大功能,它允许您轻松管理对象(代表您的复选框列表)。更少的代码并且易于维护。然而,在某些情况下,我们希望跟踪更改并做其他事情(我的意思是除了检查/取消检查操作之外)。

例如:

 $scope.toggleSelect = function toggleSelect(code)
 {
  /**/
 AsyncService.doStuff();
 }

Is there anything wrong with this approach?

没有错,但这种方法(在您的情况下)类似于 javascript native。所以我们失去了 Angular 优势。 我会使用模型绑定(bind)并在 $scope.options(甚至是 $watchCollection)上实现 $watch。像这样的东西:

$scope.$watch(function () {
    return $scope.options; // listen on model watch
},
function (newValue, oldValue) {
    /* any checkbox clicked */
}, true);

Are there any caveats I must beware of when updating the model from the controller?

别这么想,流程很简单。

关于javascript - 将复选框绑定(bind)到 Angular 模型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22835055/

相关文章:

Jquery - 获取 3 个随机数组元素而不交叉

javascript - 需要通过javascript和php从检查的项目中提取数据库信息

angularjs - 如何修复找不到模块 Graceful-fs 错误?

javascript - 在 Angular 组件中共享大的 json 数据是好是坏?

javascript - 如何在angularjs中对ng-disabled进行检查?

php - 如何更改两个单词之间的文本?

javascript - 从文件中加载一个 javascript 对象及其函数

javascript - 我可以检测到用户在 IE8-9 中打开开发者工具吗?

javascript - Jest 模拟内部函数

java - Java 数组多项式加减法