javascript - $watch not detecting model change with checkbox -
i'm trying relatively simple in angular , can't figure out why it's not working. want perform 1 function when checkbox checked , different function when it's unchecked.
so tried use ng-model evaluate foo true or false if checkbox checked or unchecked , if statement pick function. {{foo}} in view switches true/false console.log says undefined. know why?
html:
<div ng-repeat="element in elements"> <input type="checkbox" ng-model="foo" /> {{foo}} </div> script:
$scope.$watch('foo', function(){ console.log($scope.foo); }); edit: oops! had in repeat. there way achieve effect inside repeat?
what did
your watcher outside ngrepeat. ngmodel inside ngrepeat.
what wrong
the inner ngmodel creates foo property on inner scope. watcher reads not existing foo property of outer scope.
solution
have model object example, attached outer scope
$scope.model = { foo: false }; have inner ngmodel set model.foo.
what difference ?
using solution, ngmodel gets right model object because of scope inheritance, not try when assigning foo property without traversing prototype chain in wrote.
Comments
Post a Comment