0

I have a directive that use keypup to prevent any null value, the min value must be always 1, it also bound to ng-model and ng-change without rely on the directive.

View

<input class="form-control numberOfUsesMustNotNull" type="number" placeholder="Qty" ng-model="qty" ng-change="updatePrice (qty)" />

Directive

.directive('numberOfUsesMustNotNull', function() {
    return {
        restrict: 'C',
        link: function(scope, element, attrs) {
            element.bind('keyup', function($event) {
                // disallow number of uses to be zero
                if(element.val() === '' || element.val() === 0){
                  element.val(1);
                }
            });
        }
    }
});

The problem here is when the condition in the directive been triggered, the updatePrice function in my controller won't trigger. How do I trigger controller's $scope.updatePrice from directive? I think I should not just set the DOM value, but have access to $scope.qty in the directive.

Try this fiddle http://jsfiddle.net/67s2ktfz/, backspace the number, it will changed back to one but the total isn't updated.

Jessie Emerson
  • 743
  • 4
  • 12
  • 25
  • Possible duplicate of [Angular: calling controller function inside a directive link function using &](http://stackoverflow.com/questions/16839259/angular-calling-controller-function-inside-a-directive-link-function-using) – Tah Dec 17 '16 at 03:28
  • Hey Jessie, as an aside of what Tah linked - do you know about the min & max attributes you can use a on a number type input? You could put min="1" and if they do lower than that it would mark the input invalid/undefined if you check the ng-model. Doesn't answer your question but prevents the need of a custom directive. – IfTrue Dec 17 '16 at 03:34
  • @IfTrue min='1' doesn't prevent the keypress – Jessie Emerson Dec 17 '16 at 03:42
  • @TahTatsumoto http://jsfiddle.net/67s2ktfz/ try to use a hit backspace, you will know my problem, the link doesn't help, it's a different situation. – Jessie Emerson Dec 17 '16 at 03:52
  • @georgeawg this is too complicated, why not just pass the $scope from directive to controller? or vice versa as there's alrdy 2 way binding. – Jessie Emerson Dec 17 '16 at 04:14

0 Answers0