Search code examples
jqueryangularjsformsraty

JQuery Raty And Angular - Adding form validation


I have created a form to include a textarea and a JQuery Raty plugin. The Raty plugin is added using an Angular directive which include a custom form validation making sure user actually rated. My form submit button is depend on the form $valid state.

The problem is that my form.$valid value isn't refreshed after i set the validity of my raty - it takes another user action in the form to refresh that value.

e.g. if user entered a review in the text area and after that rated button would still be disabled, only after he enter another character in the review text area button state will refresh.

How do i apply the change in raty validity on the form.$valid immediately?

Thanks!

My code:

.directive("ngRaty", function() {
    return {
        require: 'ngModel',
        restrict: 'E',
        link: function(scope, elem, attrs,ctrl) {
            ctrl.$setValidity('ngRaty',false);
            $(elem).raty({score: attrs.score,
                          number: attrs.number,
                          path: '/resources/img/',
                          hints: ['Awaful', 'Bad', 'Ok', 'Good', 'Excellent'],
                          click: function (score, evt) {
                              scope.feedbackDetails.score=score;
                              ctrl.$setValidity('ngRaty',true);
                          }
                }
            )

        }
    }
});


<form name="feedbackForm" class="form-horizontal" novalidate>
    <ng-raty ng-model="feedbackDetails.score" required></ng-raty>
    <textarea name="review" ng-model="feedbackDetails.review" required></textarea>
    <button ng-click="submitFeedback(feedbackDetails)" ng-disabled="!feedbackForm.$valid">Submit</button>
</form>

Solution

  • You need to apply the scope after the click event.

    click: function (score, evt) {
        scope.feedbackDetails.score=score;
        ctrl.$setValidity('ngRaty',true);
        scope.$apply();
    }