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
答案 0 :(得分:1)
_.last(..., 2)
会返回一个包含2个项目的数组。
var x = _.last($scope.awesomeThings, 2);
_.each
遍历数组,所以:
_.each([x], function(i) {
注意你是如何不必要地将x
包装在另一个数组中的。
它成功遍历数组中唯一的项,这是另一个包含所需数据的数组。
您的解决方案应该简单:
_.each(x, function(i) {
alert(i);
});
或者更简单,就像你已经注意到你可以这样做:
_.each(x, alert);
答案 1 :(得分:0)
我找到了我正在寻找的解决方案。
这两行解决了我的问题
var x = _.last($scope.awesomeThings, 2);
_.each(x.reverse(), alert);
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);
});*/
});