Preena Khanuja
Preena Khanuja

Reputation: 205

How to copy entire object in angularjs?

being a newbie to angular got stuck in copying json data, I need to copy my entire json object to clipboard , and then paste it later on. have done it through ngClip , but it dosen't copy the entire object else it copies the object name.below is what I've done so far:

<label>Copy #1</label>

<button class="btn btn-default" clip-copy="copy1">Copy!</button>
<script>
   var myapp = angular.module('myapp', ["ngClipboard"]);

   myapp.config(['ngClipProvider', function(ngClipProvider) {
      ngClipProvider.setPath("//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/2.1.6/ZeroClipboard.swf");
   }]);

   myapp.controller('myctrl', function($scope) {
      $scope.copy1 = {};
      $scope.copy1.Name = "ABC";
      $scope.copy1.age = 24;
      $scope.copy1.City = "Pittsburgh";

   });
</script>

Clicking on Copy! button always copies copy1, I want it to copy the entire object.However if I give copy1.Name in clip-copy it copies ABC. Any leads wud be appreciated.

Upvotes: 0

Views: 1270

Answers (3)

P&#229;l
P&#229;l

Reputation: 988

It's probably because copy1 is an object. Try using angular.toJson() to convert the object to a string. Like this:

<label>Copy #1</label>

<button class="btn btn-default" clip-copy="test()">Copy!</button>
<script>
   var myapp = angular.module('myapp', ["ngClipboard"]);

   myapp.config(['ngClipProvider', function(ngClipProvider) {
      ngClipProvider.setPath("//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/2.1.6/ZeroClipboard.swf");
   }]);

   myapp.controller('myctrl', function($scope) {
      $scope.copy1 = {};
      $scope.copy1.Name = "ABC";
      $scope.copy1.age = 24;
      $scope.copy1.City = "Pittsburgh";

      $scope.test = function () {
        return angular.toJson($scope.copy1);
      }

   });
</script>

Plunker: http://plnkr.co/edit/KISecLdBfOMxVPFT6MMZ?p=preview

Upvotes: 2

Shashank Dhar
Shashank Dhar

Reputation: 119

Use angular.copy($scope.copy1,$scope.target) . it will copy your entire copy1 object to target object.

Upvotes: 0

Shreyas
Shreyas

Reputation: 1937

Use JSON.stringify(obj) to convert your object to string. It will return you a string which you can copy on clip board.

Upvotes: 2

Related Questions