I am trying to bind a checkbox to scope using ng-model. The checkbox's initial state corresponds to the scope model just fine, but when I check/uncheck the checkbox, the model does not change. Some things to note is that the template is dynamically loaded at runtime using ng-include
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"/>
When I check the box the console logs false, when I uncheck the box, the console again logs false. I also have an order model on the scope, and if I change the checkbox's model to be order.billing_is_shipping, it works fine
If the template is loaded using
ng-include
, you need to use$parent
to access the model defined in the parent scope sinceng-include
if you want to update by clicking on the checkbox.DEMO
I struggled with this problem for a while. What worked was to bind the input to an object instead of a primitive.
In my directive (in the link function) I had created scope variable success like this:
And in the scope template included input tag like:
This did not work.
In the end I changed my scope variable to look like this:
And my input tag to look like this:
It now works as expected. I knew an explanation for this, but forgot, maybe someone will fill it in for me. :)
Expanding on Matt's answer, please see this Egghead.io video that addresses this very issue and provides an explanation for: Why binding properties directly to $scope can cause issues
see: https://groups.google.com/forum/#!topic/angular/7Nd_me5YrHU