0

I have an AngularJS 1.5 directive:

var assetSearchService = function(proService) {
    var assets = [];

    var searchAssets = function(searchTerm){
        proService.searchAssets(searchTerm).then(function(data){
            assets = data.data;
        });
    };

    return {
        searchAssets, searchAssets,
        assets: assets
    };
};

When I try to use assetSearchService.assets in my controller after calling search, the data is not set in assetService.assets.

If I log the data after the searchAssets promise returns, I am getting data.

this.assets does not work so how do I do get the variable back from the callback?

4
  • 1
    instead of replacing assets inside your callback, you should be pushing the data into the existing array. try assets = assets.concat(data.data); Commented Aug 21, 2016 at 1:44
  • No, assets does not reference the originally declared var assets. Commented Aug 21, 2016 at 1:46
  • 1
    it does, but you are replacing it inside the callback with a different array, which breaks the angular bindings Commented Aug 21, 2016 at 1:49
  • I tried it your way, and even tried your way with dumping the whole service with a $timeout and the assets are never assigned to the original var assets Commented Aug 21, 2016 at 10:39

2 Answers 2

1

Found an answer. Neither assets = newArray nor conact does not work because both return a new array and break the reference, rather than modifying the current one.

This works:

Array.prototype.push.apply(assets, data.data);

Here's a working example: https://jsfiddle.net/mbaranski/5k4bqo0z/

Sign up to request clarification or add additional context in comments.

Comments

0

You can achieve more complex solution

var assetSearchService = function(proService) {
  service = this;
  service.assets = [];

  service.searchAssets = function(searchTerm){
    proService.searchAssets(searchTerm).then(function(data){
        assets.push(data.data);
    });
  };

  return service;
};

1 Comment

This does not answer the question, because the whole problem is emptying the assets array and adding each item from data.data to the new array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.