AngularJS Sticky Notes - Alternate
Thanks Ali Mills for the inspiration!
http://jsfiddle.net/alimills/rCbMv
And Thomas Burleson for some great feedback on the code.
HTML
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js"></script>
<div ng-app="myApp">
<ul class="thumbnails">
<li ng-repeat="note in notes">
<my-note class="span2 thumbnail">
<button class="btn btn-large close pull-right" ng-click="ondelete({note: note})">×</button>
<hr/>
<p>{{note.title}}</p>
</my-note>
</li>
</ul>
</script>
<div ng-controller="NotebookCtrl">
<div class="page-header">
<h1>AngularJS Sticky Notes</h1>
</div>
<div class="form-actions">
<div class="input-append">
<form ng-submit="addNote(noteTitle);resetForm();">
<input class="span3" ng-model="noteTitle" size="16" type="text" placeholder="Add a note">
<button class="btn btn-success" type="button"
ng-disabled="!noteTitle" ng-click="addNote(noteTitle);resetForm();">Add Note
</button>
</form>
</div>
</div>
<my-notebook notes="getNotes()" ondelete="deleteNote(note)"></my-notebook>
</div>
</div>
CSS
.ui-state-highlight { background-color: #EEEEEE; }
JavaScript
angular.module('myApp', [])
.service('notesService', function () {
var data = [
{id:1, title:'Note 1'},
{id:2, title:'Note 2'},
{id:3, title:'Note 3'},
{id:4, title:'Note 4'},
{id:5, title:'Note 5'},
{id:6, title:'Note 6'},
{id:7, title:'Note 7'},
{id:8, title:'Note 8'}
];
return {
notes:function () {
return data;
},
addNote:function (noteTitle) {
data.push({
id:data.length + 1, title:noteTitle
});
},
deleteNote:function (note) {
// I changed this, to use object reference, instead of id
data.splice(data.indexOf(note), 1);
}
};
})
.directive('myNotebook', function () {
return {
restrict:"E",
scope:{
notes:'=',
ondelete:'&'
},
templateUrl:"partials/notebook-directive.html"
// I removed the controller
};
})
.directive('myNote', function () {
return {
// I removed the isolate scope
restrict:'E',
link:function (scope, element, attrs) {
element.hide().fadeIn('slow');
$('.thumbnails').sortable({
placeholder:"ui-state-highlight", forcePlaceholderSize:true
});
}
};
})
.controller('NotebookCtrl', ['$scope', 'notesService', function ($scope, notesService) {
$scope.getNotes = function () {
return notesService.notes();
};
$scope.addNote = function (noteTitle) {
if(noteTitle != '') {
notesService.addNote(noteTitle);
}
};
$scope.deleteNote = notesService.deleteNote;
$scope.resetForm = function() {
...