0

I have outputted a variable that is an array within my view and while it is displaying the values as following :-

Inbound bound posts will contain ["phone", "car"]

How do I change this to display this in a human format eg. (as below)

Inbound bound posts will contain phone, car

5 Answers 5

4

if you simply want to list the array you can use join:

arr = ["phone", "car"];
arr.join(", ");

would output: "phone, car".

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

Comments

2

To make array displayed as series of texts

Inbound bound posts will contain {{ ["phone", "car"].join(', ') }}

1 Comment

It is better to keep the logic out of the view.
1

Create a method on your controller to handle the array->string:

let arrayToWrite = ['phone', 'car'];
aToS() {
  return arrayToWrite.join(' ');
}

Then your view:

Inbound bound posts will contain {{ vm.aToS() }}

(assuming 'vm' is your controller, as per standard convention)

You could input the array to the method too, if you need, rather than defining the array outside the method.

Comments

1

There are many alternatives. You could also do this:

    <div>
      Inbound bound posts will contain
      <span ng-repeat="obj in objects">{{obj}} </span>
    </div>

and in your controller hold the list on scope:

$scope.objects = ["car", "phone"];

Comments

1

You could use a filter:

myApp.filter('join', function () {
    return function join(array, separator, prop) {
        if (!Array.isArray(array)) {
            return array; // if not array return original - can also throw error
        }

        return (!!prop ? array.map(function (item) {
            return item[prop];
        }) : array).join(separator);
    };
});

And in your HTML, simply write this:

<div ng-controller="MyCtrl">
  Inbound bound posts will contain {{things | join: ', ' }}
</div>

A working JSFiddle: http://jsfiddle.net/Lvc0u55v/12345/

8 Comments

Question have Array in view.So Is code have higher priority than data??
Best practice is to keep the logic out of the view. You should define your array in your controller for example. This is also needed for unit testing, code readability, reusability etc etc.
Then why are you using expressions inside your view?
Isn't that the whole purpose of Angular? ;-)
using expressions inside the code is also not a best practice,lets use ng-bind and change the code.
|

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.