2014-10-01 90 views
23

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

我希望你們能解釋我爲什麼這不起作用,以及如何解決這個問題...

回答

63

您需要調用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(); 
    } 

Plnkr

默認實現$render做到這一點: -

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

但是你可以重寫和自定義實施$render以及..

+2

太容易了。調用$ render並且它可以工作。這很酷。但我真的需要覆蓋$ render,因爲在1.3.0-rc.3中,$ render()看起來幾乎相同,但它會檢查$ isEmpty(ctrl。$ modelValue)而不是$ isEmpty(ctrl。$ viewValue)。那麼在setViewValue中,modelValue只有在有效時才被設置。但我希望無效的字段也可以重新渲染。如果沒有覆蓋渲染的行爲就像它曾經做過一樣(就像在你的答案中一樣),我的領域是空的。現在我已經重寫了渲染方法。我想知道他們爲什麼改變渲染方法。 – Allisone 2014-10-02 09:45:06

-3

嘗試範圍。 $ apply()在模型上調用更改,因爲您喜歡更改模型超出了ngModel的範圍

+0

'scope。$ apply()'不適用於我。調用$ setViewValue(...)我認爲已經觸發了$ apply的任何操作,因爲當我調用$ setViewValue時,該模型上的手錶會熄滅。 – Jerinaw 2016-02-17 18:37:03