我有一个对象数组,每个对象都有带日期的参数,所以我希望在ng-repeat
中的元素之间经过一个日期。为此,我写了一个指令并在元素之前附加日期
。在代码中工作正常,但.before
或elem.parent().append("date is here")
无效。我错了,为什么元素不会在ng-repeat
的元素之前附加?
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js@*" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="ctrl">
<div ng-repeat="doc in array" divider>
{{doc.name}}
</div>
<script>
angular.module('myApp', [])
.controller('ctrl', function($scope) {
$scope.array = [{
name: 'Document from John Doe',
date: "2017-05-30T11:05:59.118+0300"
},{
name: "Document from Lisa Ginx",
date: "2017-05-24T13:51:09.736+0300"
},{
name: "Document from Crazy Kid",
date: "2017-05-24T13:51:09.736+0300"
}, {
name: "Untitled Document",
date: "2017-05-18T13:51:09.736+0300"
}]
})
.directive('divider', [
function() {
return {
link: function(scope, elem, attr) {
var dates = {'1': 'January', '2': 'February', '3': 'March', '4': 'April', '5': 'May', '6': 'June', '7':'July', '8':'August', '9': 'September', '10': 'October', '11': 'November', '12': 'December'}
var next = scope.$index + 1,
prevMonth = scope.array[next] ? new Date(scope.array[next].date).getMonth() + 1 : null,
prevDay = scope.array[next] ? new Date(scope.array[next].date).getDate() : null;
var current = scope.$index,
currentMonth = new Date(scope.array[current].date).getMonth() + 1,
currentDay = new Date(scope.array[current].date).getDate();
if( prevDay !== currentDay )
angular.element(elem).after('<div style="font-style:italic">--'+ dates[currentMonth] + " " + currentDay +'--</div>');
// angular.element(elem).before('<div style="font-style:italic">--'+ dates[currentMonth] + " " + currentDay +'--</div>');
// elem.parent().append('<div style="font-style:italic">--'+ dates[currentMonth] + " " + currentDay +'--</div>')
}
};
}
]);
</script>
</body>
</html>