Jez Jez - 5 months ago 8
PHP Question

New lines not working in Javascript function when echoing in PHP

This code below uses Javascript and PHP, but when it runs I want each echo to be on a separate line. I have tried using \n and <br> and other methods but all of them dont have any effect on the text. Can anyone please help me?



function MyCtrl($scope) {
$scope.environment_service_packages =
[
{name: 'obj1', info: {text: '<?php echo "hello" . "\n" . "<br>" . "world"; ?>', show: true}},
{name: 'obj2', info: {text: 'some extra info for obj2', show: false}},
];
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app>
<table ng-controller="MyCtrl" class="table table-hover table-striped">
<tr class="info">
<td>...</td>
</tr>
<tbody ng-repeat="x in environment_service_packages">
<tr ng-click="x.info.show = !x.info.show">
<td> {{ x.name }}
</tr>
<tr ng-show="x.info.show">
<td>
{{ x.info.text }}
</td>
</tr>
</tbody>
</table>
</body>





Edit: For some reason this snippet does not interpret the php.

Answer

You just need to put the expression between <pre></pre> tags:

<td>
    <pre>{{ x.info.text }}</pre>
</td>

And then use \n as a line break (Forget the <br>).

Here's a working example. I removed the PHP tags and used plain text for the demo:

text: 'line 1\nline 2'

BTW - You can replace the PRE tags with a white-space: pre; css style.

function MyCtrl($scope) {
  $scope.environment_service_packages = 
    [
      {name: 'obj1', info: {text: 'line 1\nline 2', show: true}},
      {name: 'obj2', info: {text: 'some extra info for obj2', show: false}},
    ];
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app>
  <table ng-controller="MyCtrl" class="table table-hover table-striped">
    <tr class="info">
      <td>...</td>
    </tr>
    <tbody ng-repeat="x in environment_service_packages">
      <tr ng-click="x.info.show = !x.info.show">
        <td> {{ x.name }}
      </tr>
      <tr ng-show="x.info.show">
        <td>
          <pre>{{ x.info.text }}</pre>
        </td>
      </tr>
    </tbody>
  </table>
</body>

Comments