Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度ng模型不使用初始值复选框_Javascript_Angularjs - Fatal编程技术网

Javascript 角度ng模型不使用初始值复选框

Javascript 角度ng模型不使用初始值复选框,javascript,angularjs,Javascript,Angularjs,角度v1.5x 还有许多其他问题听起来很相似,但没有一个解决了我的问题,所以我加上这个是为了节省其他人的时间 这不起作用: app.controller("Controller", function($scope) { $scope.foo.bar = "true" } <input type="checkbox" ng-model="foo.bar" /> app.controller("Controller", function($scope) { $scope.fo

角度v1.5x

还有许多其他问题听起来很相似,但没有一个解决了我的问题,所以我加上这个是为了节省其他人的时间

这不起作用:

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

<input type="checkbox" ng-model="foo.bar" />
app.controller("Controller", function($scope) {
  $scope.foo.bar = true
}

<input type="checkbox" ng-model="foo.bar" />
app.controller(“controller”),函数($scope){
$scope.foo.bar=“true”
}

双向绑定实际上正在工作。但是第一次加载时不会选中复选框。

这确实有效:

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

<input type="checkbox" ng-model="foo.bar" />
app.controller("Controller", function($scope) {
  $scope.foo.bar = true
}

<input type="checkbox" ng-model="foo.bar" />
app.controller(“controller”),函数($scope){
$scope.foo.bar=真
}
请注意,在这个版本中,
foo.bar
的值是一个布尔值。经过数小时的挫折,我学到了一个艰难的方法,即复选框上的
ng model
不适用于任何真实值

奖金提示:

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

<input type="checkbox" ng-model="foo.bar" />
app.controller("Controller", function($scope) {
  $scope.foo.bar = true
}

<input type="checkbox" ng-model="foo.bar" />
这在许多其他问题中都有指出,但值得在此重复。当您直接绑定到基本体而不是属性时,Angular有时会表现出不可预测的行为。翻译:始终在
ng模型中包含

好:
ng model=“foo.bar”

错误:
ng model=“foobar”