-3

Im trying to convert an array of Strings, to a single string. I made a quick plunker of what I need in basic terms:

https://plnkr.co/edit/t2KeZJ8yOtDo2KxDQuzD?p=preview

In the app Im working on I need to use two different controllers and I created a factory for the controllers to share data, so I set the example up like that.

Here is the function I am trying to use to loop the array and add to a scope variable, with CherryPick being the array:

cherryCtrl.CherryPick = CherryPick.list;
cherryCtrl.string = cherryCtrl.output;


cherryCtrl.runString = function createString(array) {

    angular.forEach(cherryCtrl.CherryPick, function (object) {
        angular.forEach(object, function (value, key) {
            cherryCtrl.output += value + '  ';

            console.log(cherryCtrl.output);
        });
    });
    return cherryCtrl.output;

}

the console for output gives:

undefinedHello World  
undefinedHello World  object:5  
undefinedHello World  object:5  Goodbye World  
undefinedHello World  object:5  Goodbye World  object:8 

Which is confusing.

I took the idea for the loop from here:

Array to string angular

Any pointer would be mucho appreciated

12
  • there is no value assigned to cherryCtrl.output Commented Feb 5, 2016 at 14:07
  • What does the data in cherryCtrl.CherryPick look like? Commented Feb 5, 2016 at 14:07
  • What's confusing about that output? Commented Feb 5, 2016 at 14:07
  • 1
    Why not just array.join(' ')? Commented Feb 5, 2016 at 14:11
  • 1
    The data in cherryCtrl.CherryPick looks like {"snippet":"Hello World"} Commented Feb 5, 2016 at 14:11

1 Answer 1

0

So, main problem with this code

CherryPick.list.push({
    snippet
});

In old browser not implement ES6 this code raise exception: Syntax Error, but in new standard this

{ snippet }

is Shorthand property names (ES6), so you push to list not a string but object - {snippet: "snippetvalue"}.

After binding to view, in object added special angular property $$hashKey with value like object:5, that's why you see unexpected string in output.

For solution you can add string instead object,

CherryPick.list.push(// NOTE: without curly brackets
    snippet
);
Sign up to request clarification or add additional context in comments.

Comments

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.