scope.$watch in angular directive does not work proprely-Collection of common programming errors

I’m using Angular and Bootstrap. I’m trying to replicate the functionality of ng-model for bootstrap checkbox. What i would like to accomplish is:

i would like that when i click on the checkbox (label really) the model change, and actually that works… but what does not work that when i try to watch the object for changes the behavior is weired, because i need two click insted of one for disable or enable the checkbox. Moreover if inside the the label element that has as attribute cm-checkbox=”model.prop” i put a {{model.anotherprop}} wont work (does not render anything).

From the documentation i understood that because i want the two-way data bind the scope must be defined as i did.

Thank you for your help!

I have the following HTML:


      
      same lable text

And the following JS:

directive('cmCheckbox', function() {
  return {
    restrict: 'A',
    scope: {'cmCheckbox':'='},
    link: function(scope,elm,attrs) {
      scope.$watch('cmCheckbox', function() {
          console.log("first value for "+attrs.cmCheckbox+" is: "+scope.cmCheckbox);
          if (!scope.cmCheckbox) {
            console.log("checked");
            $(elm).removeClass("checked");
            $(elm).children("input").removeAttr("checked");
          } else { // false and undefined
            console.log("unchecked");
            $(elm).addClass("checked");
            $(elm).children("input").attr("checked","checked");
          }
      });
      $(elm).on('click', function(e) {
        e.preventDefault();
        var currentValue = elm.hasClass("checked") ? false : true;
        scope.$apply(function() {
          scope.cmCheckbox = currentValue;
        },true);
        scope.$parent.$apply();
      });
    }
  };
}).

Here is the jsFiddle: jsfiddle.net/pmcalabrese/66pCA/2

Originally posted 2013-12-02 01:31:46.