setViewValue在输入中没有更新实际可见输入值

All*_*one 26 angularjs angularjs-directive angular-ngmodel

我差不多两天都在为此而战.我希望你们能帮助我.

简介:
我在以编程方式设置某些输入字段的视图值时遇到问题.
我有一个带有输入的表单,其值在表单被删除之前保存(多个元素和多个表单可能,用户可能会关闭表单,然后重新打开).在重新打开表单时,我想恢复以前的视图值(主要原因是还要返回未保存在模型中的无效视图值).这不起作用.

如果我调用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");
            }
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我希望你们能告诉我为什么这不起作用以及如何解决这个问题......

PSL*_*PSL 78

您需要调用ngModel.$render()以在输入中反映viewvalue更改.没有创建手表,$viewValue因此更改会自动反映出来.

   function setAnotherValue() {
        ngModel.$setViewValue("I'm a new value of the model. I've been set using the setViewValue method");
        ngModel.$render();
    }
Run Code Online (Sandbox Code Playgroud)

Plnkr

默认实现$render这样做: -

 element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
Run Code Online (Sandbox Code Playgroud)

但是,您也可以覆盖和自定义您的实现$render.

  • 太简单.调用$ render并且它有效.这很酷.但是我真的需要覆盖$ render,因为在1.3.0-rc.3中$ render()看起来几乎一样,但它检查$ isEmpty(ctrl.$ modelValue)而不是$ isEmpty(ctrl.$ viewValue).好吧,在setViewValue中,仅当modelValue有效时才设置它.但我也想要重新渲染无效字段.如果没有覆盖渲染,就像它曾经一样(就像在你的答案中一样),我的字段是空的.现在我已经覆盖了渲染方法.我想知道为什么他们改变了渲染方法. (2认同)