加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – setViewValue在指令中输入不更新实际的可见输入值

发布时间:2020-12-17 08:12:52 所属栏目:安全 来源:网络整理
导读:我已经和这个战斗了差不多两天了。我希望你们能帮助我。 概要: 我有编程地设置一些输入字段的视图值的问题。 我有一个表单与输入值,在删除表单之前保存其值(可以使用多个元素和多个表单,用户可能关闭一个表单,然后重新打开)。在重新打开窗体时,我想恢复
我已经和这个战斗了差不多两天了。我希望你们能帮助我。

概要:
我有编程地设置一些输入字段的视图值的问题。
我有一个表单与输入值,在删除表单之前保存其值(可以使用多个元素和多个表单,用户可能关闭一个表单,然后重新打开)。在重新打开窗体时,我想恢复以前的视图值(主要原因是返回没有保存在模型中的无效视图值)。这不行。

如果我调用ctrl $ setViewValue(previousValue),我得到的模型(可见)被更新(如果有效),formControl的视图值(在控制台中调试)也改变了,但是我并没有将它们实际呈现在输入字段。我不明白为什么:(

我将问题减少到这个小提琴:
http://jsfiddle.net/g0mjk750/1/

JavaScript的

var app = angular.module('App',[])

    function Controller($scope) {
        $scope.form = {
            userContent: 'initial content'
        }
    }
app.controller('Controller',Controller);
app.directive('resetOnBlur',function () {
    return {
        restrict: 'A',require: 'ngModel',link: function (scope,element,attrs,ngModel) {
            element.bind('blur',function () {
                console.log(ngModel);
                scope.$apply(setAnotherValue);
            });
            function setAnotherValue() {
                ngModel.$setViewValue("I'm a new value of the model. I've been set using the setViewValue method");
            }
        }
    };
});

HTML

<form name="myForm" ng-app="App" ng-controller="Controller" class="form">
    Text: {{form.userContent}}
    <hr />
    If you remove the text,"Required!" will be displayed.<br/>
    If you change the input value,the text will update.<br/>
    If you blur,the text will update,but the (visible) input value not.
    <hr />
    <input class="input" type="text" ng-model="form.userContent" name="userContent" reset-on-blur required></textarea>
    <span ng-show="myForm.userContent.$error.required">Required!</span>
</form>

我希望你们可以向我解释为什么这不起作用,如何解决这个问题?

您需要调用 ngModel.$render()以使视图值更改反映在输入中。在$ viewValue上没有创建手表,以便自动反映更改。
function setAnotherValue() {
        ngModel.$setViewValue("I'm a new value of the model. I've been set using the setViewValue method");
        ngModel.$render();
    }

Plnkr

$ render的默认实现会这样做:

element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);

但是,您可以覆盖并自定义$ render的实现。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读