111

在 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()返回值更改模型或视图。我怎样才能做到这一点?

4

23 回答 23

45

显然,这是 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 初始化的时候都没有……所以这是一个很难解决的问题。

于 2013-02-19T20:25:50.803 回答
35

这是一个比其他解决方案更简单的解决方案,并且在语义上是合理的 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>
于 2014-01-12T09:22:35.870 回答
35

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

我认为它更 Angularish 并且不依赖于 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"/>
于 2013-11-08T08:28:13.197 回答
12

无需再破解!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

在页面中的 jQuery 或 Angularautofill-event.js 之后添加脚本。

这将执行以下操作:

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

API(手动触发检查):

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

这个怎么运作

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

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

依赖项

AngularJS 或 jQuery(与其中之一或两者一起使用)

更多信息和来源在github 页面

可以在此处阅读Github 上的原始 Angular Issue #1460 。

于 2014-09-05T13:47:10.790 回答
10

脏代码,在使用此代码之前检查问题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);
                   }
               };
});
于 2013-05-28T20:33:28.227 回答
5

似乎是明确的直接解决方案。不需要 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();
        }
    }
}]);
于 2013-11-22T16:03:06.540 回答
4

解决方案 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 [使用角度事件]:

参考:Becko 的回答

指示:

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>
于 2014-05-28T18:36:26.293 回答
4

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

指示:

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 类在所有输入上触发事件。

于 2013-09-06T21:31:27.480 回答
3

这是 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 /> 
于 2013-10-22T04:46:04.893 回答
1

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

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

于 2014-03-24T01:43:48.013 回答
1

这是另一种不那么棘手的解决方法,但需要在控制器中添加一些额外的代码。

HTML:

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

指令(CoffeeScript):

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

控制器:

controllers.controller 'FormController', [->
    $scope.submitForm = ->
        username = $scope.getUsername?() ? $scope.username
        # HTTP stuff...
]
于 2013-06-19T19:11:22.433 回答
1

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

这是我的代码:

module.directive('autoFill', [ function() {
    return {
        require: 'ngModel',
        link:function(scope, element, attr, ngModel) {
            var origVal = element.val();
            if(origVal){
                ngModel.$modelValue = ngModel.$modelValue || origVal;
            }
        }
    };
}]);
于 2014-08-21T00:14:47.883 回答
1

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

if (!$scope.model) $scope.model = $('#input_field').val();
于 2013-10-18T16:21:37.047 回答
0

我在提交时强制使用 $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);
于 2013-10-16T17:45:57.327 回答
0

对此答案的小修改(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
    }
  });
于 2014-03-20T20:34:22.507 回答
0

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

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

此修复程序显然非常愚蠢和hacky,但它在100%的时间内都有效 -

function myScope($scope, $timeout) {
    // ...
    (function autoFillFix() {
        $timeout(function() { 
            $('#username').trigger('change'); 
            $('#password').trigger('change'); 
            autoFillFix(); }, 500);                    
    })();
}
于 2014-04-24T00:27:23.027 回答
0

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

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

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

于 2014-02-05T09:17:20.533 回答
0

没有指令的解决方案:

.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);
    }])
于 2014-04-10T11:13:53.343 回答
0

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

.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-model 上拥有的任何解析器/格式化程序,并使提交功能透明。

于 2014-04-08T10:58:18.823 回答
0

你可以试试这段代码:

yourapp.directive('autofill',function () {

    return {
        scope: true,
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            var origVal = elem.val();
            if (origVal != '') {
                elem.trigger('input');
            }
        }
    }
});
于 2014-03-20T10:21:04.880 回答
0

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

我最终禁用了自动填充 - 并不理想,但对用户来说不会那么混乱。

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

在这里找到了答案

于 2016-06-12T19:06:42.630 回答
-1

如果您使用的是 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();
}
于 2013-10-21T15:48:16.303 回答
-1

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

在您的 Angular js 控制器中:

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

于 2014-10-04T07:17:30.870 回答