我正在尝试在Angular中创建通知徽章和一组链接。我很接近,但我遇到了两个问题。首先,我想将类从“activeLink”更改为“visitedLink”,而不是使用ng-click切换类。第二个是我只想返回徽章中归类为activeLinks的项目。
https://jsfiddle.net/mvk0851x/9/
标记
<div ng-app='deliverablesApp'>
<div class="notes" ng-controller="NoteCtrl">NOTIFICATIONS <span class="badge">{{noteCount.length}}</span>
<ul>
<li ng-repeat="note in noteCount | limitTo: 4" >
<a ng-click="changeLink = !changeLink"
ng-class="{'activeLink': !changeLink, 'visitedLink': changeLink}"
href="#"
>
{{note.update}}
</a>
<br />
<cite>{{note.date | date: 'medium'}}</cite>
</li>
</ul>
</div>
</div>
控制器
(function(){
var app = angular.module('deliverablesApp', [])
app.controller('NoteCtrl', function($scope){
$scope.noteCount = [
{
update:"Sample text for Note 1",
link:"note-update-link",
date: 1441133965418
},
{
update:"Sample text for Note 2",
link:"note-update-link",
date: 1441129965418
},
{
update:"Sample text for Note 3",
link:"note-update-link",
date: 1440629965418
},
{
update: "Sample text for Note 4",
link:"note-update-link",
date: 1440622965418
},
{
update: "Sample text for Note 5",
link:"note-update-link",
date: 1440621765418
}];
});
})();
答案 0 :(得分:2)
要对应用程序状态进行更多控制,您应该将其存储在模型中 - 而不是类列表。
据我所知,这里有两个问题:
要解决这两个问题,您应该将数据放入模型中。例如:
$scope.notes = [
{
update:"Sample text for Note 1",
link:"note-update-link",
date: 1441133965418,
visited: false
},
{
update:"Sample text for Note 2",
link:"note-update-link",
date: 1441129965418,
visited: false
},
{
update:"Sample text for Note 3",
link:"note-update-link",
date: 1440629965418,
visited: false
},
{
update: "Sample text for Note 4",
link:"note-update-link",
date: 1440622965418,
visited: false
},
{
update: "Sample text for Note 5",
link:"note-update-link",
date: 1440621765418,
visited: false
}
];
您是否在每个收藏品中看到visited: false
。
现在你可以
所以现在你的模板应该如下:
<li ng-repeat="note in notes" >
<a
ng-click="note.visited = true"
ng-class="{'activeLink': !note.visited, 'visitedLink': note.visited}"
href="#">
{{note.update}}
</a>
<br />
<cite>{{note.date | date: 'medium'}}</cite>
</li>
如果您只想获取尚未访问的项目,则应将其过滤掉:
var visitedNotes = $scope.notes.filter(function (item) {
return !item.visited;
});
下一步是创建Note
类以将此逻辑封装在其中。例如(ES6)
class Note {
constructor(params) {
Object.assign(this, params);
this.visited = false;
}
visit() {
this.visited = true;
}
}
...
$scope.notes = [
{
update:"Sample text for Note 1",
link:"note-update-link",
date: 1441133965418
},
{
update:"Sample text for Note 2",
link:"note-update-link",
date: 1441129965418
},
{
update:"Sample text for Note 3",
link:"note-update-link",
date: 1440629965418
},
{
update: "Sample text for Note 4",
link:"note-update-link",
date: 1440622965418
},
{
update: "Sample text for Note 5",
link:"note-update-link",
date: 1440621765418
}].map(function (data) {
return new Note(data);
});
...
<a ng-click="note.visit()">