I'm completely new to working with Angular, and I have a simple question about using $http and $location in directives. I'm trying to create a task list and would like to be able to delete an entry when clicking on a link.
Right now, I've applied an attribute directive to the <a>
tag and want it to send a delete request to my API when clicked. It reminds me of how you would handle this in Backbone by binding a click event that triggers a call to remove the model from the collection. So, that's how I structured my code, at least?
Directive
app.directive('delete', function() {
return {
link: function(scope, element, attrs) {
element.bind('click', function(event) {
scope.$apply(function() {
$http.delete('/api/posts/' + $routeParams.id).
success(function(data) {
$location.path('/app')
})
})
})
}
}
})
Controller
app.controller('IndexCtrl', ['$scope', '$http', '$location'
function($scope, $http, $location) {
$http.get('/api/posts').
success(function(data) {
$scope.posts = data.posts;
})
}
]);
Markup
div(ng-controller='IndexCtrl')
h1 Blog
div
a.btn(href='/app/newpost') New Post
ul
li(ng-repeat='post in posts')
a(href='/app/{{ post._id }}')
h3 {{ post.title }}
div {{ post.text }}
a(href='/app/editpost/{{ post._id }}') Edit
a(href='#', delete id='{{post._id }}') Delete