Tips for utilizing $http and $location in custom directives

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
    

Answer №1

app.directive('remove',['$http', '$location',function($http, $location) {
 //your logic ..
}]);

implementing DI for directives is similar to how you do it for controllers

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that the Bootstrap form validation checks for both an empty field and a valid URL

I'm currently working on validating a form field in Bootstrap 4.4. The goal is to not only check if the field is filled out, but also to ensure that it contains a valid URL. This URL can be an internal link, a hostname, or an IP address. However, it m ...

After clicking, revert back to the starting position

Hey there, I have a question about manipulating elements in the DOM. Here's the scenario: when I click a button, a div is displayed. After 2 seconds, this div is replaced by another one which has a function attached to it that removes the div again. ...

Handling 401 Status Codes with Access and Refresh Tokens in a React and Node Application

Dealing with a 401 status request from my server when the access token is expired is proving to be a challenge. I have implemented accessTokenVerify on the server side: require('dotenv').config(); const jwt = require("jsonwebtoken") ...

Changing the default download directory in Selenium using JavaScript

How can I use JavaScript to change the default download directory? I have a list of folders and one is named "C:\Study\Selenium". How do I update the location for downloaded files to this specific path in my code? chromeOptions.setUserPreference ...

Embed full content in iframe using bootstrap 4

Embedding an iframe of an appointment scheduling frontend on my page has been a challenge. While the width is correct, the height of the frame is too small. Despite attempting various CSS modifications, I have not been able to achieve the desired result. I ...

Having a solid grasp of React and Material UI, as well as familiarity with the concept of props and

For my react application, I utilize Material UI (@mui/material). However, I've come to realize that there might be some nuances in how the components interact with each other. For instance, if I nest a MenuItem inside a Box or a Link inside a Typograp ...

Angularjs ng-repeat function chooses the specified ID

I recently wrote an AngularJS code that allows me to navigate through a collection of values: <ul class="bullet-list" ng-repeat="item in data track by item.id" > <li><a ng-mouseover="selectedId()" ng-model="item.id" href="{{item.url}}"& ...

Include a hyperlink within every row - ngx-datatable

I am brand new to using Angular. My goal is to have a link on each row of ngx-datatable that directs me to another page when clicking on the first column of each row. This new page should be based on the row id. For example, if I have a table listing cours ...

Count of daily features in JavaScript

Suppose there is a json document structured as follows: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "time": 1438342780, "title": "Iran's foreign minister calls for world's ...

Troubleshooting: Issues with MongoDB Aggregation not reflecting updates in my collection

Currently, I am attempting to execute an aggregation query in Mongo utilizing their nodejs driver. The query involves aggregating some fields, calculating averages, and other operations. I constructed the aggregation in Mongo Cloud and then exported it to ...

Tips for saving a webcam captured image location into a MySQL database

I've been experiencing issues with the code I used to capture an image. While the image is successfully stored in the specified folder, I'm unable to store the image path in the database. The code stops executing after displaying the "Uploading.. ...

Breaking down arrays using the JADE Template Engine

Currently, I am utilizing the JADE template engine in conjunction with ExpressJS. I am attempting to pass an array to my JADE template like so: var data = { "labels" : ["Label 1", "Label 2"] }; res.render('index', {data: data}); The struct ...

Converting an enum into a key-value array in TypeScript: A simple guide

var enums = { '1': 'HELLO', '2' : 'BYE', '3' : 'TATA' }; I am seeking a solution to convert the above object into an array that resembles the following structure, [ { number:' ...

State variable in Redux is not defined

While there have been numerous similar inquiries on this platform, I haven't been able to find a solution to my particular issue. Below is the React component in question: class MyTransitPage extends Component { componentDidMount() { this.pro ...

Tips for reducing the size of your JavaScript buffer

Is it the correct way to convert a buffer to a string, trim it, and then convert back to a buffer in Node.js v6.12.x? var buf = Buffer.alloc(xxxxxx); ..... // buffer receives its value ..... let buffParsed = String.fromCharCode.apply(null, buf); buffPa ...

Managing API calls through Next.js routing

Here is a next.js handler function for handling api requests on our server. I am looking for assistance on how to access a variable between request methods. Any help would be greatly appreciated. export default function handler(req, res) { if(req.met ...

Comparing MongoDB and Express with MySQL: A Detailed Analysis

Currently in the process of deciding on tools to use for developing a software application. The system needs to handle various complexities such as: User Management (Trainer login vs Client login) Different dashboards based on user profiles W ...

Displaying data on the user interface in Angular by populating it with information from the form inputs

I am working on a project where I need to display data on the screen based on user input received via radio buttons, and apply specific conditions. Additionally, I require assistance in retrieving the id of an object when the name attribute is chosen from ...

Is it possible to access prop properties within the ready() function?

I am seeing the error message undefined in the console, specifically originating from the ready() function. The issue I am encountering is related to attempting to assign the value of this.users.name to this.userForm.name. Can someone please point out wh ...

Bootstrap button statuses confirmed

I am trying to implement a checked state for group checkboxes in Bootstrap 3.0.2. documentation This is the HTML code snippet: <div class="btn-group" data-toggle="buttons"> <label class="btn btn-default"> <input type="check ...