我一直在为此奋斗了近两天。我希望你们能帮助我。setViewValue输入指令中没有更新实际可见输入值
摘要:
我有问题以编程方式设置一些输入字段的视图值。
我有一个表单,其输入的值在表单被删除前保存(可能有多个元素和多个表单,用户可能会关闭表单并稍后重新打开)。在重新打开表单时,我想恢复以前的视图值(主要原因是还要返回未保存在模型中的无效视图值)。这不起作用。如果我调用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>
我希望你们能解释我为什么这不起作用,以及如何解决这个问题...
太容易了。调用$ render并且它可以工作。这很酷。但我真的需要覆盖$ render,因为在1.3.0-rc.3中,$ render()看起来几乎相同,但它会检查$ isEmpty(ctrl。$ modelValue)而不是$ isEmpty(ctrl。$ viewValue)。那么在setViewValue中,modelValue只有在有效时才被设置。但我希望无效的字段也可以重新渲染。如果没有覆盖渲染的行为就像它曾经做过一样(就像在你的答案中一样),我的领域是空的。现在我已经重写了渲染方法。我想知道他们为什么改变渲染方法。 – Allisone 2014-10-02 09:45:06