Michael
Michael

Reputation: 13616

How to make clone of the object in angular?

I have this nested state:

  .state("inspectionsBuilder.view", {
                    url: "/:inspectionId",
                    templateUrl: "app/inspectionsBuilder/templates/inspectionsBuilder.tmpl.html",
                    controller: "inspectionsBuilderController",
                    controllerAs: "builder",
                    resolve: {
                        inspectionCurrentIFrame: ["getCurrentIFrameService", inspectionGetCurrentListIFrameResolver]
                    },
                })

Here is function that has been called from resolve:

function inspectionGetCurrentListIFrameResolver(getCurrentIFrameService) {
    return getCurrentIFrameService;

}

getCurrentIFrameService - is factory service that return some DOM element.

From inspectionGetCurrentListIFrameResolver function i want to make clone of the getCurrentIFrameService service and return it.

function inspectionGetCurrentListIFrameResolver(getCurrentIFrameService) {
    var elem = null; 
    var result =  angular.copy(getCurrentIFrameService,elem);
    return elem;
}

But it not working.Any idea what I am missing?

Upvotes: 0

Views: 646

Answers (2)

Estus Flask
Estus Flask

Reputation: 222498

According to the manual,

Destination into which the source is copied. If provided, must be of the same type as source.

When variable reference (elem) is passed to the function (angular.copy), it can't be reassigned, that's why variable should be an object or an array, so its properties can be added/removed.

The proper way to do this is

var result = angular.copy(getCurrentIFrameService);

or

var elem = {}; 
var result = angular.copy(getCurrentIFrameService, elem);

Upvotes: 1

Wylie Kulik
Wylie Kulik

Reputation: 686

Isn't the service a Singleton ?

If you have a constructor/factory taking a json ball as argument, you can use Lodash to deep clone an arbitrarily nested json ball and then pass that to create a clone of whatever the object is.

You can read state into an object, and pass that to a constructor, assuming they are of the same type, or one could be derived from the other.

Upvotes: 0

Related Questions