In my custom directive, I add elements to the DOM based on the number of objects in my data array. I need to look at a specific property in each object. When I add these elements to the DOM, I want to set $ watch to the checked property of each object in the toppings array, but it does not work, and I donโt know why. I set a breakpoint inside the function that should be called when the property changes from true to false or false to true, but this function is never called. Is the reason obvious? I am just learning Angular, so I can easily make a stupid mistake.
$scope.bits = 66; (ie onions and olives) $scope.toppings = [ { topping: 1, bits: 2, name: 'onions' }, { topping: 2, bits: 4, name: 'mushrooms' }, { topping: 3, bits: 8, name: 'peppers' }, { topping: 4, bits: 16, name: 'anchovies' }, { topping: 5, bits: 32, name: 'artichokes' }, { topping: 6, bits: 64, name: 'olives' }, { topping: 7, bits: 128, name: 'sausage' }, { topping: 8, bits: 256, name: 'pepperoni' } ]
Each object in the model receives a new checked property, which will be true or false.
NOTE: an array of objects will contain no more than a dozen elements. Performance is not a concern.
link: function link(scope, iElement, iAttrs, controller, transcludeFn) { <snip> // At this point scope.model refers to $scope.toppings. Confirmed. angular.forEach(scope.model, function (value, key) { // bitwise: set checked to true|false based on scope.bits and topping.bits scope.model[key].checked = ((value.bits & scope.bits) > 0); scope.$watch(scope.model[key].checked, function () { var totlBits = 0; for (var i = 0; i < scope.model.length; i++) { if (scope.model[i].checked) totlBits += scope.model[i].bits; } scope.bits = totlBits; }); }); <snip>