AngularJS 浏览器自动填充解决方法是使用指令

AngularJS browser autofill workaround by using a directive

本文关键字:指令 方法 解决 浏览器 填充 AngularJS      更新时间:2023-09-26

在 AngularJS 中提交表单并使用浏览器记住密码功能时,在随后的登录尝试中,您让浏览器使用用户名和密码填写登录表单,$scope模型不会根据自动填充进行更改。

我发现的唯一肮脏的黑客是使用以下指令:

app.directive("xsInputSync", ["$timeout" , function($timeout) {
    return {
        restrict : "A",
        require: "?ngModel",
        link : function(scope, element, attrs, ngModel) {
            $timeout(function() {
                if (ngModel.$viewValue && ngModel.$viewValue !== element.val()) {
                    scope.apply(function() {
                        ngModel.$setViewValue(element.val());
                    });
                }
                console.log(scope);
                console.log(ngModel.$name);
                console.log(scope[ngModel.$name]);
            }, 3000);
        }
    };
}]);

问题是ngModel.$setViewValue(element.val());不会根据element.val()返回值更改模型或视图。我怎样才能做到这一点?

显然,

这是 Angular 的已知问题,目前处于打开状态

我不确定除了像您正在尝试的某种解决方法之外,您还能在这里做什么。看来你走在正确的轨道上。我无法让我的浏览器尝试记住您的 plunk 的密码,所以我不确定这是否有效,但请看一下:

app.directive('autoFillSync', function($timeout) {
   return {
      require: 'ngModel',
      link: function(scope, elem, attrs, ngModel) {
          var origVal = elem.val();
          $timeout(function () {
              var newVal = elem.val();
              if(ngModel.$pristine && origVal !== newVal) {
                  ngModel.$setViewValue(newVal);
              }
          }, 500);
      }
   }
});
<form name="myForm" ng-submit="login()">
   <label for="username">Username</label>
   <input type="text" id="username" name="username" ng-model="username" auto-fill-sync/><br/>
   <label for="password">Password</label>
   <input type="password" id="password" name="password" ng-model="password" auto-fill-sync/><br/>
   <button type="submit">Login</button>
</form>

我认为你只需要简化一下你的方法。我绝对推荐的一件事是检查ngModel.$pristine并确保你没有覆盖一些糟糕的用户的输入。此外,3 秒可能太长了。顺便说一句,您不必在$timeout中调用$apply((,它应该自动为您排队$digest。

真正的问题:你的浏览器会击败Angular执行吗?我的浏览器呢?

这可能是一场无法取胜的战争,这就是为什么Angular(或Knockout(无法轻易解决它的原因。在指令的初始执行时,无法保证输入中的数据状态。甚至在Angular初始化的时候也没有。所以这是一个很难解决的问题。

这是一个解决方案,它远没有提出的其他解决方案那么笨拙,并且在语义上是合理的 AngularJS: http://victorblog.com/2014/01/12/fixing-autocomplete-autofill-on-angularjs-form-submit/

myApp.directive('formAutofillFix', function() {
  return function(scope, elem, attrs) {
    // Fixes Chrome bug: https://groups.google.com/forum/#!topic/angular/6NlucSskQjY
    elem.prop('method', 'POST');
    // Fix autofill issues where Angular doesn't know about autofilled inputs
    if(attrs.ngSubmit) {
      setTimeout(function() {
        elem.unbind('submit').submit(function(e) {
          e.preventDefault();
          elem.find('input, textarea, select').trigger('input').trigger('change').trigger('keydown');
          scope.$apply(attrs.ngSubmit);
        });
      }, 0);
    }
  };
});

然后,您只需将指令附加到表单中:

<form ng-submit="submitLoginForm()" form-autofill-fix>
  <div>
    <input type="email" ng-model="email" ng-required />
    <input type="password" ng-model="password" ng-required />
    <button type="submit">Log In</button>
  </div>
</form>

您不必使用 $timeout 或类似的东西。您可以使用事件系统。

我认为它更棱角分明,不依赖于jQuery或自定义事件捕获。

例如,在您的提交处理程序上:

$scope.doLogin = function() {
    $scope.$broadcast("autofill:update");
    // Continue with the login.....
};

然后你可以有一个这样的autofill指令:

.directive("autofill", function () {
    return {
        require: "ngModel",
        link: function (scope, element, attrs, ngModel) {
            scope.$on("autofill:update", function() {
                ngModel.$setViewValue(element.val());
            });
        }
    }
});

最后,你的HTML将是这样的:

<input type="text" name="username" ng-model="user.id" autofill="autofill"/>

无需再破解了!Angular dev tbosch 制作了一个 polyfill,当浏览器更改表单字段而不触发更改事件时,它会触发更改事件:

https://github.com/tbosch/autofill-event

目前,他们不会将其构建到 Angular 代码中,因为这是浏览器的错误修复,并且也可以在没有 Angular 的情况下工作(例如,对于普通的 jQuery 应用程序(。

"polyfill 将检查文档加载时以及何时留下输入(仅以相同的形式(进行更改。但是,如果需要,可以手动触发检查。

该项目有单元测试和半自动测试,所以我们终于有一个地方来收集所有不同的用例以及所需的浏览器设置。

请注意:此 polyfill 适用于普通的 AngularJS 应用程序、AngularJS/jQuery 应用程序,也适用于不使用 Angular 的普通 jQuery 应用程序。

它可以安装:

bower install autofill-event --save

页面中将脚本autofill-event.js添加到jQuery或Angular之后

这将执行以下操作:

  • 在 DOMContentLoaded 之后:检查所有输入字段
  • 剩下一个字段:检查同一表单中的所有其他字段

API(手动触发检查(:

    $el.checkAndTriggerAutoFillEvent():对
  • 给定的jQuery/jQLite元素中的所有DOM元素执行检查。

工作原理

  1. 记住用户(侦听更改事件(和JavaScript(通过拦截jQuery/jQLite元素的$el.val(((对输入元素的所有更改。该更改的值存储在私有属性中的元素上。

  2. 检查元素是否自动填充:将元素的当前值与记住的值进行比较。如果不同,请触发更改事件。

依赖

AngularJS或jQuery(与其中一个或两个一起工作(

更多信息和来源在 github 页面上。

Github上的原始角度问题#1460可以在这里阅读。

脏代码,请在使用此代码之前检查问题 https://github.com/angular/angular.js/issues/1460#issuecomment-18572604 是否已修复。此指令在字段填充时触发事件,而不仅仅是在提交之前(如果您必须在提交之前处理输入,这是必需的(

 .directive('autoFillableField', function() {
    return {
                   restrict: "A",
                   require: "?ngModel",
                   link: function(scope, element, attrs, ngModel) {
                       setInterval(function() {
                           var prev_val = '';
                           if (!angular.isUndefined(attrs.xAutoFillPrevVal)) {
                               prev_val = attrs.xAutoFillPrevVal;
                           }
                           if (element.val()!=prev_val) {
                               if (!angular.isUndefined(ngModel)) {
                                   if (!(element.val()=='' && ngModel.$pristine)) {
                                       attrs.xAutoFillPrevVal = element.val();
                                       scope.$apply(function() {
                                           ngModel.$setViewValue(element.val());
                                       });
                                   }
                               }
                               else {
                                   element.trigger('input');
                                   element.trigger('change');
                                   element.trigger('keyup');
                                   attrs.xAutoFillPrevVal = element.val();
                               }
                           }
                       }, 300);
                   }
               };
});

似乎是明确的直接解决方案。不需要jQuery。

更新:

  • 仅当模型值不等于实际输入时,才会更新模型价值。
  • 检查不会在首次自动填充时停止。如果您想使用例如另一个帐户。

app.directive('autofillable', ['$timeout', function ($timeout) {
    return {
        scope: true,
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            scope.check = function(){
                var val = elem[0].value;
                if(ctrl.$viewValue !== val){
                    ctrl.$setViewValue(val)
                }
                $timeout(scope.check, 300);
            };
            scope.check();
        }
    }
}]);

解决方案 1 [使用 $timeout]:

命令:

app.directive('autoFillSync', function($timeout) {
    return {
      require: 'ngModel',
      link: function(scope, elem, attrs, model) {
          var origVal = elem.val();
          $timeout(function () {
              var newVal = elem.val();
              if(model.$pristine && origVal !== newVal) {
                  model.$setViewValue(newVal);
              }
          }, 500);
      }
    };
});

.HTML:

<form name="myForm" ng-submit="login()">
  <label for="username">Username</label>
  <input type="text" id="username" name="username" ng-model="username" auto-fill-sync/><br/>
  <label for="password">Password</label>
  <input type="password" id="password" name="password" ng-model="password" auto-fill-sync/><br/>
  <button type="submit">Login</button>
</form>

解决方案 2 [使用角度事件]:

参考:贝科的答案

命令:

app.directive("autofill", function () {
    return {
        require: "ngModel",
        link: function (scope, element, attrs, ngModel) {
            scope.$on("autofill:update", function() {
                ngModel.$setViewValue(element.val());
            });
        }
    };
});

.HTML:

<form name="myForm" ng-submit="login()">
  <label for="username">Username</label>
  <input type="text" id="username" name="username" ng-model="username" autofill/><br/>
  <label for="password">Password</label>
  <input type="password" id="password" name="password" ng-model="password" autofill/><br/>
  <button type="submit">Login</button>
</form>

解决方案 3 [使用中继方法调用]:

命令:

app.directive('autoFill', function() {
    return {
        restrict: 'A',
        link: function(scope,element) {
            scope.submit = function(){
                scope.username = element.find("#username").val();
                scope.password = element.find("#password").val();
                scope.login();//call a login method in your controller or write the code here itself
            }
        }
    };
});

.HTML:

<form name="myForm" auto-fill ng-submit="submit()">
   <label for="username">Username</label>
   <input type="text" id="username" name="username" ng-model="username" />
   <label for="password">Password</label>
   <input type="password" id="password" name="password" ng-model="password" />
   <button type="submit">Login</button>
</form>

好吧,最简单的方法是模拟浏览器的行为,所以如果 change 事件有问题,就自己触发它。简单得多。

命令:

yourModule.directive('triggerChange', function($sniffer) {
    return {
        link : function(scope, elem, attrs) {
            elem.on('click', function(){
                $(attrs.triggerChange).trigger(
                    $sniffer.hasEvent('input') ? 'input' : 'change'
                );
            });
        },
        priority : 1
    }
});

.HTML:

<form >
    <input data-ng-model="user.nome" type="text" id="username">
    <input data-ng-model="user.senha" type="password" id="password" >
    <input type="submit" data-ng-click="login.connect()" id="btnlogin" 
           data-trigger-change="#password,#username"/>
</form>

您可以执行一些变体,例如将指令放在表单上,并在表单提交时使用 .dirty 类在所有输入上触发事件。

这是jQuery的方式:

$(window).load(function() {
   // updates autofilled fields
   window.setTimeout(function() {
     $('input[ng-model]').trigger('input');
   }, 100);
 });

这是角度方式:

 app.directive('autofill', ['$timeout', function ($timeout) {
    return {
        scope: true,
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            $timeout(function(){
                $(elem[0]).trigger('input');
                // elem.trigger('input'); try this if above don't work
            }, 200)
        }
    }
}]);

.HTML

<input type="number" autofill /> 
<</div> div class="answers">

这是另一种不太笨拙的解决方法,但需要在控制器中执行一些额外的代码。

.HTML:

<form ng-submit="submitForm()" ng-controller="FormController">
    <input type="text" ng-model="username" autocomplete-username>
    <input type="submit">
</form>

指令(咖啡脚本(:

directives.directive 'autocompleteUsername', ->
    return (scope, element) ->
        scope.getUsername = ->
            element.val()

控制器:

controllers.controller 'FormController', [->
    $scope.submitForm = ->
        username = $scope.getUsername?() ? $scope.username
        # HTTP stuff...
]

这是我发现的唯一允许我的所有 Angular 验证按设计工作的解决方案,包括禁用/启用提交按钮。 使用 bower 和 1 个脚本标记进行安装。 巴辛加!

https://github.com/tbosch/autofill-event

更改模型值,而不是使用超时函数对我有用。

这是我的代码:

module.directive('autoFill', [ function() {
    return {
        require: 'ngModel',
        link:function(scope, element, attr, ngModel) {
            var origVal = element.val();
            if(origVal){
                ngModel.$modelValue = ngModel.$modelValue || origVal;
            }
        }
    };
}]);

提交处理程序中的单行解决方法(需要 jQuery(:

if (!$scope.model) $scope.model = $('#input_field').val();

我在提交时强制使用$setValue(val(((:(这在没有jQuery的情况下工作(

   var ValidSubmit = ['$parse', function ($parse) {
    return {
        compile: function compile(tElement, tAttrs, transclude) {
            return {
                post: function postLink(scope, element, iAttrs, controller) {
                    var form = element.controller('form');
                    form.$submitted = false;
                    var fn = $parse(iAttrs.validSubmit);
                    element.on('submit', function(event) {
                        scope.$apply(function() {
                            var inputs = element.find('input');
                            for(var i=0; i < inputs.length; i++) {
                                var ele = inputs.eq(i);
                                var field = form[inputs[i].name];
                                field.$setViewValue(ele.val());
                            }
                            element.addClass('ng-submitted');
                            form.$submitted = true;
                            if(form.$valid) {
                                fn(scope, {$event:event});
                            }
                        });
                    });
                    scope.$watch(function() { return form.$valid}, function(isValid) {
                        if(form.$submitted == false) return;
                        if(isValid) {
                            element.removeClass('has-error').addClass('has-success');
                        } else {
                            element.removeClass('has-success');
                            element.addClass('has-error');
                        }
                    });
                }
            }
        }
    }
}]
app.directive('validSubmit', ValidSubmit);

我对 Angularjs 很陌生,但我找到了解决这个问题的简单方法=>强制角度重新评估表达式...通过改变它!(当然你需要记住初始值才能恢复到初始状态(以下是控制器函数中提交表单的方式:

    $scope.submit = function () {
                var oldpassword = $scope.password;
                $scope.password = '';
                $scope.password = oldpassword;
//rest of your code of the submit function goes here...

当然,在密码输入中输入的值是由Windows而不是用户设置的。

你可以试试这段代码:

yourapp.directive('autofill',function () {
    return {
        scope: true,
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            var origVal = elem.val();
            if (origVal != '') {
                elem.trigger('input');
            }
        }
    }
});

对这个答案的一个小修改(https://stackoverflow.com/a/14966711/3443828(:使用$interval而不是$timeout,这样你就不必与浏览器竞争。

mod.directive('autoFillSync', function($interval) {
    function link(scope, element, attrs, ngModel) {
        var origVal = element.val();
        var refresh = $interval(function() {
          if (!ngModel.$pristine) {
            $interval.cancel(refresh);
          }else{
            var newVal = element.val();
            if (origVal !== newVal) {
              ngModel.$setViewValue(newVal);
              $interval.cancel(refresh);
            }
          }
        }, 100);
    }
    return {
      require: 'ngModel',
      link: link
    }
  });

这是我最终在表单中使用的解决方案。

.directive('autofillSync', [ function(){
  var link = function(scope, element, attrs, ngFormCtrl){
    element.on('submit', function(event){
      if(ngFormCtrl.$dirty){
        console.log('returning as form is dirty');
        return;
      }   
      element.find('input').each(function(index, input){
        angular.element(input).trigger('input');
      }); 
    }); 
  };  
  return {
    /* negative priority to make this post link function run first */
    priority:-1,
    link: link,
    require: 'form'
  };  
}]);

表单的模板将是

<form autofill-sync name="user.loginForm" class="login-form" novalidate ng-submit="signIn()">
    <!-- Input fields here -->
</form>

通过这种方式,我能够运行我在 ng 模型上拥有的任何解析器/格式化程序,并使提交功能透明。

没有指令的解决方案:

.run(["$window", "$rootElement", "$timeout", function($window, $rootElement, $timeout){
        var event =$window.document.createEvent("HTMLEvents");
        event.initEvent("change", true, true);
        $timeout(function(){
            Array.apply(null, $rootElement.find("input")).forEach(function(item){
                if (item.value.length) {
                    item.$$currentValue = item.value;
                    item.dispatchEvent(event);
                }
            });
        }, 500);
    }])

这是一个简单的修复程序,适用于我在Firefox和Chrome中测试过的所有情况。请注意,对于最高答案(带超时的指令(,我遇到了问题 -

  • 浏览器后退/前进按钮,不要重新触发页面加载事件(因此修复不适用(
  • 在页面加载后的一段时间内加载凭据。 例如,在 Firefox 中,双击登录框并从存储的凭据中进行选择。
  • 需要一个在表单提交之前更新的解决方案,因为我禁用了登录按钮,直到提供有效输入

这个修复程序显然非常愚蠢和黑客,但它在 100% 的时间内有效 -

function myScope($scope, $timeout) {
    // ...
    (function autoFillFix() {
        $timeout(function() { 
            $('#username').trigger('change'); 
            $('#password').trigger('change'); 
            autoFillFix(); }, 500);                    
    })();
}
<</div> div class="answers">

这些解决方案都不适合我的用例。我有一些使用 ng-change 来观察变化的表单字段。使用 $watch 没有帮助,因为它不是由自动填充触发的。由于我没有提交按钮,因此没有简单的方法来运行某些解决方案,并且我没有成功使用间隔。

我最终禁用了自动填充 - 不理想,但对用户的困惑要少得多。

<input readonly onfocus="this.removeAttribute('readonly');">

在这里找到答案

如果你使用的是jQuery,你可以在表单提交时这样做:

.HTML:

<form ng-submit="submit()">
    <input id="email" ng-model="password" required 
           type="text" placeholder="Your email">
    <input id="password" ng-model="password" required 
           type="password" placeholder="Password">
</form>

.JS:

 $scope.submit = function() {
     $scope.password = $('#password').val();
}

如果你想保持简单,只需使用 javascript 获取值

在你的角度js控制器中:

var username = document.getElementById('username'(.value;