0

i am leaning how to use underscore in AngularJS. i try to extract last 2 element from array and show in alert. code is working but the problem is last two element is showing together in alert but i want to show each element in alert one after one. here is my code. please tell me what i should use as a result each last 2 element in alter one after one.

<div ng-app="myApp" ng-controller="MainCtrl">

</div>

var myApp = angular.module('myApp', []);

myApp.factory('_', function() {
  return window._; //Underscore should be loaded on the page
});

myApp.controller('MainCtrl', function ($scope, _) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS2',
      'AngularJS1'
    ];

    var x = _.last($scope.awesomeThings, 2);
        //alert(x[0]);

        _.each([x],function(i)
    {
        alert(i);
    });

  });        

i also follow these links

how to break the _.each function in underscore.js

how to install underscore.js in my angular application?

Plucking an Object in an array using underscore.js

Monojit Sarkar
  • 2,353
  • 8
  • 43
  • 94

2 Answers2

1

_.last(..., 2) will return an array containing 2 items for you.

var x = _.last($scope.awesomeThings, 2);

_.each loops through the array, so:

_.each([x], function(i) {

Notice how you wrapped x in another array, unnecessarily. It successfully loops through the only item in the array, which is another array containing the data you needed.

Your solution should be as simple as:

_.each(x, function(i) {
  alert(i);
});

Or simpler, like you already noticed you can do:

_.each(x, alert);
casraf
  • 21,085
  • 9
  • 56
  • 91
0

i found out the solution what i was looking for.

these two line solve my issue

var x = _.last($scope.awesomeThings, 2);
_.each(x.reverse(), alert);

full code example

var myApp = angular.module('myApp', []);

myApp.factory('_', function() {
  return window._; //Underscore should be loaded on the page
});


myApp.controller('MainCtrl', function ($scope, _) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS2',
      'AngularJS1'
    ];
    //alert('pp');
    /*_.each([1,2,3],function(i)
    {
        alert(i);
    });*/
    var x = _.last($scope.awesomeThings, 2);
    _.each(x.reverse(), alert);
        //alert(x[0]);

        /*_.each([x],function(i)
    {
        alert(i);
    });*/

  });        
Monojit Sarkar
  • 2,353
  • 8
  • 43
  • 94