我已经和这个战斗了差不多两天了。我希望你们能帮助我。
概要:
我有编程地设置一些输入字段的视图值的问题。
我有一个表单与输入值,在删除表单之前保存其值(可以使用多个元素和多个表单,用户可能关闭一个表单,然后重新打开)。在重新打开窗体时,我想恢复以前的视图值(主要原因是返回没有保存在模型中的无效视图值)。这不行。
如果我调用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();
- }
$ render的默认实现会这样做:
- element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
但是,您可以覆盖并自定义$ render的实现。