我正在使用Angular,Express,Node,mySQL堆栈设置应用程序,我遇到了绑定复选框值的问题。 mySQL将布尔值存储为一点,以便json响应返回{done:1},但angular似乎只接受布尔值或字符串值绑定到true / false。
我有以下模型(我也尝试将完成定义为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设置为整数。
如何使用角度来处理数据库存储的位值?
更新:我已经更新了我的节点服务器,将done值转换为一个运行良好的布尔值。这是推荐的解决方案还是有更好的方法来实现这一目标? (这个解决方案对我来说感觉有些苛刻,我觉得必须有一种内置的方法来实现这一点,而无需在节点中重写服务器响应)
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);
});
答案 0 :(得分:0)
<input type="checkbox" ng-model="mymodel.myvalue" ng-true-value="1" ng-false-value="0" value="myvalue">
答案 1 :(得分:0)
最好的方法是使用ng-true-value和ng-false-value,我遇到了一个问题,因为我的值是作为json_encoded数组发送的,这意味着我必须包含引号以使其正确比较。< / p>
脚本:
// 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">