angularjs ng-paste不更新模型值

时间:2014-10-27 07:58:14

标签: angularjs angularjs-scope angularjs-ng-model

我在textarea中使用了ng-paste,同时粘贴了textarea中的链接,我正在调用一个自定义函数来存储该值。请参考以下代码

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

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

但是在控制台中总是得到undefined值。如何获取对象值?

2 个答案:

答案 0 :(得分:5)

将模型传递给函数并没有多大意义,因为您已经指定了ng-model,因此当用户在textbox中键入某些内容时,它的值将会更新。如果您想跟踪更改,可以为模型设置$watch或使用ng-change指定功能。

如果你想知道用户粘贴了什么,那就是另一个故事。处理ng-paste可能很棘手。要访问实际的事件,最简单的方法是在jQuery之前添加angularjs,然后执行以下操作:以下内容:

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

答案 1 :(得分:0)

在模型更新后,只需使用$timeout调用粘贴回调即可。

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