将javascript传递给angularjs只显示第一个值

时间:2018-06-09 22:07:18

标签: javascript angularjs

尝试通过调用javascript getelementby Id()函数来构建angularjs的复制和粘贴。

我在数据库中有3行,但每次单击 CopyText 按钮时,只会复制第一行(例如标题1)。如果我尝试复制第2行(例如标题2)上的文字,则会再次复制第一行。

现在我决定实现 angular.copy()功能,但它会显示  值未定义。以下是脚本

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">

<div ng-repeat="post in posts">
  <form>
    <br> post Title<br>


<input type="text"  id="post.title" ng-model="post.title">

<button  id='but_save{{$index}}' ng-click="myFunction_copy(post)">Copy text</button><br>
</form>
</div>

<script>

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http, $parse) {

  $scope.posts = [
    {
      "pid" : "1",
      "title" : "title1"
    },
    {
      "pid" : "2",
      "title" : "title2"
    },
    {
      "pid" : "3",
      "title" : "title3"
    },
  ]



$scope.post = {}; 
$scope.myFunction_copy = function(post){
var copyText = document.getElementById("post.title");

//var copyText =angular.element(document.getElementById('post.title'));
  //var copyText = angular.copy("post.title"); 

alert(post.title);



  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}


});

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的input元素都具有相同的ID:post.title(字面意思!)。您将要使用动态检索的帖子标题,您必须使用双括号:

<input type="text"  id="{{post.title}}" ng-model="{{post.title}}">

同样,您的JS代码正在使用文字名称input检索post.title元素。你应该删除双引号并执行:

var copyText = document.getElementById(post.title);