0

Following is my code for checkbox and directive.

When user click on checkbox i wants to know the current state of checkbox. It is not working now

<input type="checkbox" name="fromExistingOffer" ng-model="formData.fromExistingOffer" toggle-existing-offer>


appModule.directive('toggleExistingOffer', function() {
      return function(scope, element) {
        element.bind('click', function() {
            alert(element.attr('checked')); // help needed here

        });
      };
    });
4
  • as far as you not creating isolated scope for your directive, shouldn't model be available via scope.formData.fromExistingOffer ? Commented Dec 16, 2014 at 15:23
  • why do you want that custom directive? Why don't you just use ng-change instead? Commented Dec 16, 2014 at 15:31
  • What happens if you change attr to prop? Commented Dec 16, 2014 at 15:36
  • Your custom directive is registering a click event on the checkbox in order to check if the checkbox is checked or not. Why in the world would you want to create a directive like that? Why don't you just use either ng-click or ng-change. Then if you wan to know if the checkbox is checked just use the model: formData.fromExistingOffer. Commented Dec 16, 2014 at 15:42

3 Answers 3

1

You already have access to the scope in your directive, I would just use that.

element.bind('click', function(){
  alert(scope.formData.fromExistingOffer);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You miss a scope.$apply()... See also this working fiddle...

<input type="checkbox" name="fromExistingOffer" ng-model="formData.fromExistingOffer" toggle-existing-offer>

appModule.directive('toggleExistingOffer', function() {
  return function(scope, element) {
    element.bind('click', function() {
      scope.$apply(function () { // help given here :-)
        alert(element.attr('checked'));
      });
    });
  };
});

UPDATE: sorry, fiddle was wrong, just updated it right now... :-)

Comments

0

i tried this and worked awesome thanks "mrberggg"

appModule.directive('toggleExistingOffer', function() {
      return function(scope, element) {
        element.bind('change', function() {
            alert(scope.formData.fromExistingOffer);

        });
      };
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.