1

Probably it's a dumb question but I can't really get out of it. In a AngularJS webapp I've splitted with a filter a String got from a JSON I can't modify: now the whole string (date+hour) is divided into an array made of 2 elements(array[0]=date, array[1]=hour), but I don't know how to get only the first one in the HTML.

I can't pass the single element as a scope and I can't use the ng-repeat because I have to assign different class to every element.

HTML:

<span class="time">{{manif.avvenimento.data | split:' '}}</span>

Result printed in HTML:

["03/02/2014","20:40"]

I need to get something like this:

<span class="A">03/02/2014</span>
<span class="B">20:40</span>

Thank you all!

Pawel Miech
  • 7,742
  • 4
  • 36
  • 57
peppeuz
  • 231
  • 5
  • 13

3 Answers3

2

I would place the two strings in a separate object. That way you won't be performing the string split on every digest cycle, which is better for performance.

In your controller:

$scope.timestamp = {
    'date': '',
    'time': ''
}

$scope.$watch(manif.avvenimento.data, function (newValue, oldValue) {
    $scope.timestamp.date = ... // Place the date here
    $scope.timestamp.time = ... // Place the time here
});

In your HTML:

<span class="time">{{timetamp.time}}</span>
<span class="date">{{timetamp.date}}</span>
MW.
  • 12,550
  • 9
  • 36
  • 65
  • As I said, I can't modify the string using the scope, because it was part of a bigger scope made of element I need to repeat. – peppeuz Feb 03 '14 at 15:32
  • @peppeuz: Can't you change the scope at all? The downside with the chosen answer is that the split is performed twice each time the scope is dirty checked, which happens *very often* in Angular. This can slow the application down, especially if you combine it with ng-repeat. My answer didn't answer your specific question, but keep it in mind if your application ever starts to run slow. More info about digest and performance: http://stackoverflow.com/a/9693933/179024 – MW. Feb 03 '14 at 22:11
0

Most probably this will do:

<span class="date">{{ (manif.avvenimento.data | split:' ')[0] }}</span>
<span class="time">{{ (manif.avvenimento.data | split:' ')[1] }}</span>
Nikos Paraskevopoulos
  • 39,514
  • 12
  • 85
  • 90
  • Thanks, it worked! :) I was trying to work with the ng-if="$index==0" and so on, but your solution is exactly what I needed. I couldn't hope it wuold work this way :) – peppeuz Feb 03 '14 at 15:31
0

To get the JSON array from your back-end, add the following to your AngularJS controller:

var dtRes = $resource('URL to your resource object');
$scope.dtArr = dtRes.query();

Then iterate through it in your HTML using:

<li data-ng-repeat="dt in dtArr">
    <span>{{dt.date}} {{dt.time}}</span>
</li>
user2845946
  • 1,755
  • 29
  • 38