Attaching to directive parameters

I've been working on creating a draggable div with the ability to bind its location for further use. I'm aiming to have multiple draggable elements on the page. Currently, I've implemented a 'dragable' attribute directive that allows me to drag the element around using 'x' and 'y' attributes to set the initial location.

<body ng-app="myApp" ng-controller="myCtrl">
    <div dragable x="50" y="50" style="...."></div>
    <p>
        x: {{x_loc}}<br/>
        y: {{y_loc}}
    </p>
<body>

However, I encountered an issue when attempting to bind 'x' and 'y' to variables in the scope of myCtrl

<div dragable x="{{x_loc}}" y="{{y_loc}}" style="...."></div>

This resulted in a generic invalid expression error. My directive code is as follows:

app.directive("dragable", function($document) {
    dragable = {};

    dragable.restrict = 'A',
    dragable.link = function(scope, element, attrs) {

        element.css({
            top: scope.y + 'px',
            left: scope.x + 'px'
        });

        function select(evt) {
            ...           // get initial conditions 
            $document.on('mousemove',move);
            $document.on('mouseup',deselect);
        };

        function move(evt){
            ...          // perform error checking then
                         // update the location of the element
        };

        function deselect(evt){
            $document.unbind('mousemove',move);
            $document.unbind('mouseup',deselect);
        };        

        $document.on('mousedown', select);
    };
    dragable.scope = {
        x: "=",
        y: "=",
    };

    return dragable;
});

If anyone has suggestions on how to resolve this issue, I would greatly appreciate it. Thank you!

Answer №1

<div with-draggable x="x_loc" y="y_loc" style="...."></div> 

rather than

<div with-draggable x="{{x_loc}}" y="{{y_loc}}" style="...."></div>

due to

 with-draggable.scope = {
    x: "=",
    y: "=",
};

if you use x: "@", x="{{x_loc}}" will work

https://jsfiddle.net/1x0bxncp/1/

Answer №2

There seems to be an issue with dragable.scope = {}.

  • Single binding
    Utilize {{}} brackets within the attribute. In the scope, use x: "@x_loc"
  • Double binding
    Reference the value from the scope without brackets. In the scope, use y: "=y_loc"
    You can exclude names such as x: "=x_loc" if they are the same. Like so, x: "="

Answer №3

Make sure to eliminate the brackets in the scope properties like this:

<div draggable x="x_position" y="y_position" style="...."></div>

Additionally, don't forget to include position:absolute in your CSS style.

Check it out here

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

Inspect every div for an id that corresponds to the values stored in an array

I am in the process of developing a series of tabs based on a preexisting set of categories using the JavaScript code below. Now, I am looking to expand this functionality to target specific IDs within the DIV ID corresponding to values from an array in JS ...

Challenges with rendering items in a FlatList component in React Native

I'm currently working on transferring data from a data.json file to video.js <Image source={{ uri: video.snippet.thumbnails.medium.url }} style={{ height: 200 }} /> and I want this file to be rendered in a flatlist <FlatList showsHorizo ...

Guide on incorporating a refresh button to automatically update information from a database in MaterialUI's Datagrid

Recently diving into JavaScript, I encountered a common issue: The data for my table is sourced from a MySQL database through Axios Whenever CRUD operations are performed in the web app, the database is updated accordingly Although backend changes ...

Delete the value from the array and refresh the HTML with the updated total amount, or display '$' if there is no total amount

Currently, I have two inputs: debit and credit. On button click events, they update an array called 'debits'. Debit adds positive values while credit adds negative values. The next step is to sum the values in the array and assign it to a variab ...

Using Node.js to Insert Data into MySQL

I recently started experimenting with node.js and decided to use node-mysql for managing connections. Even though I am following the basic instructions from the github page, I am unable to establish a simple connection successfully. var mysql = require(& ...

What is the best 'event' to pair with an <input/> element in iOS/Android development?

Looking for a way to toggle results when a user starts typing in a search field? Here are some event options: mousedown / mouseup touchstart / touchend focus You could also consider using the "change" event instead of "click" to check for text input an ...

Configuring properties for a component by retrieving data from MongoDB using an API request

My current API call utilizes axios in the following format: Service.get('path/to/api', (status, data) => { this.setState({ ComponentData: data, loaded: true}); }); {this.state.loaded && <Component id={this.state.ComponentD ...

Conflict between Angular's ng-repeat directive and Sass styling

Currently, I am working on a project and encountering an issue that is causing some difficulty: In order to create a navigation bar with equally distributed list elements based on the number of items, I am utilizing ng-repeat for data binding and Sass for ...

Output JSON data using Javascript

Here is some JSON data I am working with: { "lang": [ { "SECTION_NAME": { "english": "My title" }, "SECTION_NAME_2": { "english": "My title" } } ] } I ...

unable to insert logo into HTML

I am customizing an HTML template, but the dimensions of the logo in the template are smaller than my logo. Despite adding my logo to the template, it is not showing up. @media (max-width: 673px) { #logo { margin-left: 20px; } } #header #logo ...

What could be the reason for the defaultCommandTimeout not functioning as expected in my script

Is there a way to wait for only one particular element in Cypress without having to add wait commands everywhere in the test framework? I've come across the solution of adding defaultCommandTimeout in the cypress.json file, but I don't want it t ...

Encountering problem with image file encoding while using res.download in Express.js

My node.js server with expressjs is set up for local development, where I store and retrieve various files through basic HTTP calls. Most of the time, everything works smoothly. However, on rare occasions, a small number of files return to the end-user sig ...

Using PHP to read an image blob file from an SVG

Currently, I am utilizing the Raphael JS library on the client-side to generate a chart in SVG format. However, my goal is to make this chart downloadable, which poses a challenge since SVG does not natively support this feature. Initially, I attempted to ...

Filtering and selecting tables in HTML

I am dealing with an HTML table that combines static data and MySQL input. The filtering functionality is working properly, but I am struggling to add the options "yes" and "no" to the selection list. These values are test inputs fetched from MySQL. I need ...

What methods can I use to transfer data from one domain to another domain utilizing Ajax JSONP?

Example: The URL of my site is "http://localhost:54887/CustomOrdering.html", but I want to retrieve data from another site "http://localhost:27746/Orders.aspx". In order to do this, I have implemented the following code in my CustomOrdering.html: function ...

Flaw in Basic Function Logic Using HTML, JavaScript, and CSS

Need some help with the function onBall3Click1 (code is at the bottom). The ball should act like a lightbulb: ON - turn YELLOW, OFF - turn GRAY. I've been trying to figure out the logic behind it for so long and can't seem to find the issue... ...

When the page first loads, the slider is responsive, but it does not adjust

I installed the Moving Boxes plugin and customized it to create a full-width image slider. While it works well when the page loads, I'm facing challenges with making it responsive on resize. It appears that the JS script sets fixed widths upon load, w ...

Can you explain how to use a toggle switch to make a select dropdown select a random option?

Currently, I am in the process of setting up a page for a character generator. Users will have the option to randomize traits or input their own. The interface includes toggle switches for the "choice vs random" options for each trait category, as well as ...

Tips for debugging Angular applications with Firebug

I've encountered an issue while developing an AngularJS app that fetches data from the Firebase cloud. The data is successfully displayed on the page, however, during debugging of my controller, I noticed that the variable appears to be empty. Why is ...

The menu isn't displaying properly and the onclick function seems to be malfunctioning

My onclick event is acting strange. Whenever I click the mobile menu in the menubar, it just appears briefly like a flash and then disappears. It's not staying stable on the screen. The classes are being added and removed abruptly when I try to click ...