我一直在爲此奮鬥了近兩天。我希望你們能幫助我。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