【问题标题】:Angular.js binding checkbox value to mySQL bitAngular.js 将复选框值绑定到 mySQL 位
【发布时间】:2015-03-29 07:33:42
【问题描述】:

我正在使用 Angular、Express、Node、mySQL 堆栈设置应用程序,但在绑定复选框的值时遇到问题。 mySQL 将布尔值存储为一点,因此 json 响应返回 { done: 1 },但是 angular 似乎只接受布尔值或字符串值以绑定到 true/false。

我有以下模型(我也尝试将 done 定义为 DataTypes.BOOLEAN 无济于事):

var Todo = sequelize.define('todos', {
    text: DataTypes.STRING,
    done: DataTypes.INTEGER
  })

我的代码将该模型的值设置为:

{"todos":[
    {"id":1,"text":"add my first todo","done":1},
    {"id":2,"text":"Get the done toggle working","done":0}
]}

最后在我看来我有这个代码(我正在使用玉):

li(ng-repeat="todo in todos")
    input(type="checkbox", ng-model='todo.done') 
    {{todo.text}}

但是该复选框未被选中。我尝试添加 ng-true-value 但由于它只接受字符串值,我无法将 true 设置为整数。

如何让 Angular 使用数据库存储的位值?

更新:我已更新我的节点服务器,将 done 的值转换为运行良好的布尔值。这是推荐的解决方案还是有更好的方法来实现这一点? (这个解决方案对我来说有点hacky,我觉得必须有一个内置的方法来完成这个而不重写节点中的服务器响应)

todos.retrieveAll(function(todos) {
    if(todos) {
        todos.forEach(function(todo) {
            todo.done = Boolean(todo.done);
        });
        res.json({
            todos: todos
        });
    } else {
        res.send(401, "No todos found");
    }
}, function(err) {
    res.send(501, "Error retrieveing todos. Message: " + err);
    console.log("Error: " + err);
});

【问题讨论】:

    标签: mysql angularjs data-binding


    【解决方案1】:
    <input type="checkbox" ng-model="mymodel.myvalue" ng-true-value="1" ng-false-value="0" value="myvalue">
    

    【讨论】:

    • 欢迎来到 stackoverflow.com。如果您想回答问题,请尝试使用正确的代码和解释进行解释。见How do I write a good answer?
    【解决方案2】:

    最好的方法是使用 ng-true-value 和 ng-false-value,我遇到了一个问题,因为我的值是作为 json_encoded 数组发送的,这意味着我必须包含引号才能正确比较。

    脚本:

    // this is the model object that is bound to by the checkbox (amongst other things) 
    // and in my case is "1" for true "0" for false - note this is an array as passed back from my data source so I am using [0] in the HTML ng-model - if you have a straight object then you would bind to myScopeBoundVar and it would be defines as something like {"active":1} or in my case the 1 would be a string.
    
    myScopeBoundVar=[{"active":"1", "surname" : "Smith"}];
    

    HTML

    <input value="check" ng-model="myScopeBoundVar[0].active" ng-true-value="'1'" ng-false-value="'0'" class="ng-valid ng-dirty ng-valid-parse ng-touched">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多