我正在尝试在 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>
Controller
(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
}];
});
})();
最佳答案
要更好地控制应用程序状态,您应该将其存储在模型中 - 而不是类列表中。
据我了解,这里有两个问题:
- 点击其中一项会触发所有项目更改 className。
- 第一行显示的通知数量错误。
要解决这两个问题,您应该将数据放入模型中。例如:
$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()">
关于javascript - 尝试在 AngularJS 中创建通知徽章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32173253/