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

标签 javascript mvvm angularjs

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

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

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() 的 View > 返回值。我怎样才能做到这一点?

最佳答案

Apparently this is a known issue with Angular and is currently open

除了像您尝试的那样进行某种变通之外,我不确定您还能在这里做什么。看来你在正确的轨道上。我无法让我的浏览器尝试记住你的 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 吗?我的浏览器呢?

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

关于javascript - 使用指令的 AngularJS 浏览器自动填充解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14965968/

相关文章:

javascript - 如何将 Tesseract 导入 Angular2 (TypeScript)

javascript - 固定宽度和高度的灵活字体大小

javascript - 关于Javascript闭包的问题

MVVM View 事件 Viewmodel 命令绑定(bind)

javascript - 如何使用混合 webapp(MPA 和 SPA 结合)

javascript - 结合 JS 框架

javascript - 如何 mvvm 数据绑定(bind)剑道单选按钮值属性?

c# - 数据绑定(bind)到文本框并在整个项目中共享对象

c# - WPF/MVVM : Sync scrolling of two datagrids in different views

angularjs - Angular JS 自定义指令 - 属性绑定(bind)到字符串或范围变量