Angular ng-model不使用复选框作为初始值

时间:2016-12-03 22:05:40

标签: javascript angularjs

Angular v1.5x

还有很多其他问题听起来很相似,但没有一个问题解决了我的问题,所以我添加这个以试图节省别人的时间。

这项工作

app.controller("Controller", function($scope) {
  $scope.foo.bar = "true"
}

<input type="checkbox" ng-model="foo.bar" />

双向绑定实际上正在发挥作用。但是首次加载时不会检查复选框。

1 个答案:

答案 0 :(得分:1)

这项工作:

app.controller("Controller", function($scope) {
  $scope.foo.bar = true
}

<input type="checkbox" ng-model="foo.bar" />

请注意,在此版本中,foo.bar的值是布尔值。我学到了很难(经过几个小时的挫折),复选框上的ng-model不适用于任何真实的价值。

奖金提示:

许多其他问题都指出了这一点,但这里值得重复。当你直接绑定到基元而不是属性时,Angular有时会表现得不可预测。翻译:始终在.中添加ng-model

好:ng-model="foo.bar"

不好:ng-model="foobar"

相关问题