How to validate form with input[type=file] in angularjs

前端 未结 2 1562
挽巷
挽巷 2020-12-14 16:49

HTML:

相关标签:
2条回答
  • 2020-12-14 17:21

    From the reference of NgModelController.$render()

    Called when the view needs to be updated. It is expected that the user of the ng-model directive will implement this method.

    You need to implement $render() to call it. You can do something like this

    myApp.directive('validFile', function () {
        return {
            require: 'ngModel',
            link: function (scope, el, attrs, ngModel) {
                ngModel.$render = function () {
                    ngModel.$setViewValue(el.val());
                };
    
                el.bind('change', function () {
                    scope.$apply(function () {
                        ngModel.$render();
                    });
                });
            }
        };
    });
    

    DEMO

    0 讨论(0)
  • 2020-12-14 17:27

    After updating to AngularJS 1.2.x the snippet looks not working properly anymore and the file input doesn't sticks with the selected file value, making the form unusable. Changing the directive back to your original one, and removing the ngModel.$render() it looks working like a charm:

    .directive('validFile', function () {
      return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, el, attrs, ngModel) {
          el.bind('change', function () {
            scope.$apply(function () {
              ngModel.$setViewValue(el.val());
            });
          });
        }
      };
    
    0 讨论(0)
提交回复
热议问题