checkbox未绑定到angularjs中的作用域

我正在尝试使用ng-model将checkbox绑定到作用域。 checkbox的初始状态对应于作用域模型,但是当选中/取消选中checkbox时,模型不会更改。 有些需要注意的是模板是在运行时使用ng-includedynamic加载的

app.controller "OrdersController", ($scope, $http, $location, $state, $stateParams, Order) -> $scope.billing_is_shipping = false $scope.bind_billing_to_shipping = -> console.log $scope.billing_is_shipping <input type="checkbox" ng-model="billing_is_shipping"/> 

当我检查框时,控制台logging为false,当我取消选中该框时,控制台再次logging为false。 我也有一个订单模型的范围,如果我改变checkbox的模型是order.billing_is_shipping,它工作正常

我一直在努力解决这个问题。 什么工作是绑定input到一个对象,而不是一个原语。

 <!-- Partial --> <input type="checkbox" ng-model="someObject.someProperty"> Check Me! // Controller $scope.someObject.someProperty = false 

如果使用ng-include加载模板,如果要通过单击checkbox来更新,则需要使用$parent来访问自ng-include以来在父范围中定义的模型。

 <div ng-app ng-controller="Ctrl"> <div ng-include src="'template.html'"></div> </div> <script type="text/ng-template" id="template.html"> <input type="checkbox" ng-model="$parent.billing_is_shipping" ng-change="checked()"/> </script> function Ctrl($scope) { $scope.billing_is_shipping = true; $scope.checked = function(){ console.log($scope.billing_is_shipping); } } 

DEMO

扩展Matt的答案 ,请参阅这个解决这个问题的Egghead.iovideo,并提供了一个解释: 为什么绑定属性直接到$ scope可能会导致问题

请参阅: https : //groups.google.com/forum/#!topic/angular/7Nd_me5YrHU

通常这是由于你的ng-controller和你正在创build一个新的范围的input之间的另一个指令。 当select写出它的值时,它会把它写到最近的作用域,所以它会把它写到这个作用域,而不是远离它的父对象。

最好的做法是不要直接绑定到ng-model中的variables上,这也被称为在你的ngmodel中总是包含一个“点”。

在我的指令(在链接function),我已经创build了这样的范围variables成功

 link: function(scope, element, attrs) { "use strict"; scope.success = false; 

在范围模板中包含input标签,如:

 <input type="checkbox" ng-model="success"> 

这没有奏效。

最后,我改变了我的范围variables看起来像这样:

 link: function(scope, element, attrs) { "use strict"; scope.outcome = { success : false }; 

而我的input标签看起来像这样:

 <input type="checkbox" ng-model="outcome.success"> 

现在按预期工作。 我知道这个解释,但忘了,也许有人会填补我的。 🙂