2014-10-27 157 views
1

我已經使用ng-paste作爲textarea,同時粘貼textarea中的鏈接,我正在調用一個自定義函數來存儲該值。請參考以下代碼angularjs ng-paste不更新模型值

<textarea rows="1" ng-model="myObj.content" 
       ng-paste="getContent(myObj)"> 
</textarea> 

$scope.getContent = function(a){ 
    console.log(a.content); 
} 

但是在控制檯中總是得到undefined的值。我如何獲得我的對象值?

+0

編輯我的答案,希望它有幫助! – 2014-10-27 17:49:29

回答

4

由於您已經指定ng-model,因此將模型傳遞給函數並沒有什麼意義,所以當用戶在textbox中鍵入內容時,它的值將會更新。如果您想跟蹤更改,您可以爲您的模型設置$watch或使用ng-change指定功能。

如果你想知道用戶粘貼的是什麼,那麼這是另一回事。處理ng-paste可能會很棘手。要訪問實際事件,最簡單的方法是在angularjs之前包含jQuery,然後執行以下:

HTML模板

<textarea rows="3" 
      placeholder="copy/paste here..." 
      ng-init="content = null" 
      ng-model="content" 
      ng-paste="paste($event.originalEvent)"> 
</textarea> 

控制器

$scope.paste = function (event) { 
    var item = event.clipboardData.items[0]; 
    item.getAsString(function (data) { 
    console.log(data); 
    }); 
}; 

相關plunker這裏http://plnkr.co/edit/ea5y5j


enter image description here

+0

什麼是$ event.originalEvent responsability? – 2014-11-08 16:48:48

+0

http://stackoverflow.com/q/16674963/1061668 – 2014-11-08 18:16:03

0

只需使用$timeout即可在模型更新後調用粘貼回調。

$scope.getContent = function(a){ 
    $timeout(function() {console.log(a.content)}); 
}