1

I am experiencing a really strange error. I have a checkbox in my view whose has a directive to show the value of it when it changes. In FF it works well showing the right values. But in other browsers, like Chrome, it shows the the opposite response, i.e., if is checked, should show 'true', but shows 'false'!

In my view:

<input type="checkbox" id="accept" name="accept" ng-model="accept" d6 />

My directive:

validation.directive('d6', ['$parse', function($parse){
   return {
      require: 'ngModel',
      restrict: 'A',
      link:  function link(scope, elem, attrs, control) {

         elem.on('change', function(){

             console.log(control.$modelValue);

         });

      }
 }
}]);

enter image description here

2
  • Can you supply a JS Fiddle or some more code so we don't have to rewrite everything from scratch. Commented Mar 9, 2014 at 15:05
  • Here is: jsfiddle.net/A8Vgk/306 Commented Mar 9, 2014 at 15:31

3 Answers 3

2

Angular way of doing this would be using $watch:

var myApp = angular.module('myApp',[]);

myApp.directive('d6', function(){
   return {
      require: 'ngModel',
      restrict: 'A',
      link:  function link(scope, elem, attrs, ngModel) {               
          scope.$watch(
              function () {
                  return ngModel.$modelValue;
              }, function(newValue) {
                  console.log(newValue);
              }
          );

      }
   }
});

There is working JSFiddle.

Sign up to request clarification or add additional context in comments.

Comments

2

Angular code

Found in the angular code in the checkboxInputType function used for all input[type=checkbox] with a ngModelController:

element.on('click', function() {
    scope.$apply(function() {
        ctrl.$setViewValue(element[0].checked);
    });
});

This code updates the ngModelController with the boolean as view value, instantly piped into provided parsers, thus setting the model value.

Click and change events

You are listening to the change event, which is triggered before the click event in Chrome and the opposite in firefox. That is the whole problem.

Solutions

The jQuery solution is to listen to the click event too.

The Angular solution would be to watch the model value directly.

Comments

1

Either what the two answers said, or you can simply watch for the changes in $scope.accept (which is your model):

$scope.$watch('accept', function(){
    $scope.value = $scope.accept; 
});

See it here: http://jsfiddle.net/A8Vgk/307/. This way seems the most natural to me.

1 Comment

The only drawback of this approach is that directive is usable only when scope variable name is accept.

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.