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

在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()返回的值不会更改模型或视图。我该怎么做?


ibeautiful
浏览 1006回答 3
3回答

慕田峪7331174

显然,这是Angular的已知问题,目前已打开除了像您正在尝试的工作以外,我不确定您可以在这里做什么。看来您步入正轨。我无法让我的浏览器记住您的密码,因此不确定是否可以使用,但请看一下:app.directive('autoFillSync', function($timeout) {&nbsp; &nbsp;return {&nbsp; &nbsp; &nbsp; require: 'ngModel',&nbsp; &nbsp; &nbsp; link: function(scope, elem, attrs, ngModel) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var origVal = elem.val();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $timeout(function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var newVal = elem.val();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(ngModel.$pristine && origVal !== newVal) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ngModel.$setViewValue(newVal);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, 500);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}});<form name="myForm" ng-submit="login()">&nbsp; &nbsp;<label for="username">Username</label>&nbsp; &nbsp;<input type="text" id="username" name="username" ng-model="username" auto-fill-sync/><br/>&nbsp; &nbsp;<label for="password">Password</label>&nbsp; &nbsp;<input type="password" id="password" name="password" ng-model="password" auto-fill-sync/><br/>&nbsp; &nbsp;<button type="submit">Login</button></form>我认为您只需要稍微简化一下方法即可。我绝对推荐的一件事是检查ngModel.$pristine并确保您不会覆盖某些不良用户的输入。另外,3秒可能太长。您不必在$ timeout中调用$ apply(),顺便说一句,它应该为您自动排队$ digest。真正的收获是:您的浏览器会击败Angular来执行吗?那我的浏览器呢?这可能是一场无法战胜的战争,这就是Angular(或淘汰赛)无法轻松解决它的原因。指令初次执行时,无法保证输入中数据的状态。甚至在Angular初始化时也没有。...因此,这是一个棘手的问题。
打开App,查看更多内容
随时随地看视频慕课网APP