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

前端之家收集整理的这篇文章主要介绍了angularjs – setViewValue在指令中输入不更新实际的可见输入值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经和这个战斗了差不多两天了。我希望你们能帮助我。

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

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

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

JavaScript的

  1. var app = angular.module('App',[])
  2.  
  3. function Controller($scope) {
  4. $scope.form = {
  5. userContent: 'initial content'
  6. }
  7. }
  8. app.controller('Controller',Controller);
  9. app.directive('resetOnBlur',function () {
  10. return {
  11. restrict: 'A',require: 'ngModel',link: function (scope,element,attrs,ngModel) {
  12. element.bind('blur',function () {
  13. console.log(ngModel);
  14. scope.$apply(setAnotherValue);
  15. });
  16. function setAnotherValue() {
  17. ngModel.$setViewValue("I'm a new value of the model. I've been set using the setViewValue method");
  18. }
  19. }
  20. };
  21. });

HTML

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

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

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

Plnkr

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

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

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

猜你在找的Angularjs相关文章