AngularJS复选框模型值未定义 [英] AngularJS checkbox model value is undefined

查看:47
本文介绍了AngularJS复选框模型值未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我试图将模型中的复选框的值发布到服务器,并且由于该复选框尚未与表单交互,因此我在角度时似乎没有为其分配值询问该复选框的值,它会以未定义的形式返回.

I have a problem where I'm attempting to post the value of a checkbox in my model to the server and as the checkbox has not been interacted with on the form, angular seems to have not assigned it a value, when I ask for the value of the checkbox it comes back as undefined.

这是我的标记:

<div class="form-group">
    <input id="templateDisable" type="checkbox" ng-model="template.disabled" />
    <label for="templateDisable">Disabled</label>
</div>

这是我在控制器上保存操作的简化版本:

And here's a reduced version of my save action on my controller:

$scope.save = function (form) {
    if (form.$valid) {
        var formData = new FormData();
        // this is the problem line of code
        formData.append("disabled", $scope.template.disabled);
        // ... some other stuff
    }
};

实际上,在我单击保存操作之前选中然后取消选中该复选框会导致template.disabled属性为false,这是我在没有任何手动干预的情况下所期望的.

Actually, ticking then unticking the checkbox before I hit the save action results in the template.disabled property being false, which is what I would have expected without any manual intervention.

我看过其他相关问题,例如 AngularJS:初始复选框值不在模型中,但肯定是简单的东西复选框应该被烤入?我不必一定要编写指令来确定地管理复选框吗?

I've seen other related questions, e.g. AngularJS: Initial checkbox value not in model but surely stuff like a simple checkbox should be baked in? I shouldn't have to be writing directives to manage checkboxes surely?

推荐答案

这是每个设计的.如果要在模型上使用默认值,则应在控制器内部对其进行初始化(推荐),或使用ng-init.

This is per design. If you want a default value on your model than you should initialise it inside the controller (recommended), or make use of ng-init.

app.controller('AppController',
    [
      '$scope',
      function($scope) {
        $scope.template = {
          disabled = false
        };
      }
    ]
  );

<div class="form-group">
  <input type="checkbox" ng-model="template.disabled" ng-init="template.disabled=false" />
  <label>Disabled</label>
</div>

这篇关于AngularJS复选框模型值未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆