Adjust the scope variable using a jQuery function callback

I recently discovered this code snippet:

  $scope.addName = (name) ->
    $scope.names.push name
  $(".names").draggable
    helper: "clone"
    revert: true
  $(".name-list").droppable
    accept: ".names"
    activate: ->
      $(@).addClass "bordered"
    deactivate: ->
      $(@).removeClass "bordered"
    drop: (e, ui) ->
      name = ui.draggable.attr "data-names-name"
      $scope.addName name

This piece of code allows users to drag and drop names represented as div elements onto a list. The name dragged is then added to an array.

However, I encountered an issue where the names array appears empty even after a new name has been successfully pushed into it.

Answer №1

Try enclosing it in a $scope.$apply method (apologies for not utilizing CofeeScript)

..
$scope.$apply(function(){
  $scope.addName(name);
});

Answer №2

When a script is running outside of an angular environment, it's important to manually notify Angular to update the views by triggering a digest cycle.

You can achieve this in your script by:

drop: (event, ui) ...

$(event).scope().$digest();

It appears that $scope is already accessible within the drop function, so the following code is preferred:

$scope.$digest();

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

The canvas animation in Angular with PlanetaryJS experiences glitches when switching between views

Currently, I have integrated planetaryjs into an Angular directive. Initially, the planetary rotation animation operates smoothly when the page loads. However, upon switching views and returning to the planetary animation, it starts to stutter. Check out ...

Acquire the values of keys within a JSON array

As I work on iterating through a JSON array, I am aiming to extract the key values of each record within it. At present, my JSON object presents itself in the following structure: "users": { "key_11": { "text": "11" }, "key_22": { ...

Analyzing the functionality of Express with Mocha and Chai

Currently facing an issue with testing my express server where I am anticipating a 200 response. However, upon running the test, an error occurs: Test server status 1) server should return 200 0 passing (260ms) 1 failing 1) Test server statu ...

How can you use Firestore to filter documents based on their presence in another collection?

For instance, I am looking to retrieve all users who are members of a certain "space". Here is a simplified Firestore rule example: match /users/{userId} { allow read: if exists(/databases/$(database)/documents/spaces/SPACEID/members/$(userId)); } Java ...

Obtaining an array of weeks for the previous two months from the current date using JavaScript

Looking to generate a list of weeks for the past two months using JavaScript. Any suggestions on how to accomplish this task would be greatly appreciated. [ { "week_start": "8/01/2016", "week_end": "8/06/2016" }, { "w ...

What is the functionality of an AngularJS Module?

I am curious about the inner workings of AngularJS modules After experimenting with AngularJS, I came across some puzzling observations. Including AngularJS without registering a module Upon including AngularJS without registering a module, I encountere ...

Delay the execution of the callback function until the promise has been fulfilled

I am facing an issue with a third-party library that I am listening to for events. When I try to modify the data it appends to the UI synchronously, everything works perfectly. However, once I introduce Ajax callbacks or promises into the mix, the function ...

An issue encountered with react-router-dom and the useLocation() function

Seeking guidance from experienced developers! I recently started using react-router-dom and encountered an issue with the useLocation() hook in my application. The error message states: "useLocation() may be used only in the context of a <Router> ...

Stop inserting repeatedly if there is no new data available

I'm looking for a simple way to implement an if-else statement in my AJAX code to display new data only once it's found, without repeating the same data. Also, I need to figure out how to store the last ID as a variable so that I can use it when ...

Animating the position of a div using jQuery

As I delve into the world of jQuery, I find myself navigating uncharted territory as a novice programmer. Currently, I am utilizing the animate effect to construct a horizontal navigation loop for a WordPress installation without scrolling. The animation i ...

Error message consistently pops up when using the jQuery search feature

My jQuery function is fetching data from a different domain, and I want to use AJAX to display that data when the user enters a value into the search box. However, no matter if I search by .productName or .itemCode, the app always gives me an error messa ...

(Spotify Web API) Issue with Creating New Playlist - Received Error 403 (Forbidden) upon POST request

Looking for guidance on creating a new playlist using the Web API? Check out the notes here: When making a POST request to https://api.spotify.com/v1/users/{user_id}/playlists, make sure you include the access token and data with a content type of 'a ...

Attempting to grasp the concept of Thennables within the VSCode API. Can these TypeScript code examples be considered equivalent?

I'm looking to perform a series of modifications on a document using the VSCode API. The key function in this process is Workspace.applyEdit, which gives back a Thennable. This is my first encounter with it, and the one returned from this function doe ...

How can I change the color of specific sections in a Line Chart in R Highchart?

Below is the code snippet along with the highchart chart: library(tidyverse) library(gapminder) library(highchart) highchart() %>% hc_add_series( data = gapminder %>% filter(country == 'Chile'), hcaes(x = year, y = pop), colo ...

Attaching a button to a keypress event in Vue 3.0

I'm currently trying to figure out how to trigger a button when either clicked with the mouse or when a key is pressed. I'm having trouble understanding how components communicate with each other. How can I call the pressDown() function in the Ke ...

Capturing and setting form element values within a Javascript Module Pattern

I'm looking to streamline my form element access using the Module pattern. The goal is to eliminate redundancy by organizing everything under a single module. How can I achieve this without having to directly call the Anonymous function within the mo ...

Choosing the appropriate quantity for ng-repeat values can be a simple task once you

Is there a way to implement counters for ng-repeat values individually? I have incorporated two functions, add and subtract quantity, and invoked these functions in the controller. However, the issue arises when I click on add or subtract as the counter ch ...

utilize jQuery to include a tag into every div

This is the current sample: <div class="main-wrap"> <div class="inner-wrap"> some example text here <span> <a href="1">test1</a> </span> </div> <div class="inner- ...

What is the best way to enhance an object using a class in ES6?

In an effort to improve the clarity of my ES6 class definition, my current code looks like this: class SomeClass { constructor({a, b, c, d, e}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; // additional code here ...

Generate a JavaScript File/Blob from an image's URI

Can I generate a File or Blob object from an image URI? I am utilizing the Cordova Image Picker plugin in my mobile application to retrieve photo URIs like this: "file:///data/user/0/..../image.jpg" However, I am struggling to create a File or Blob objec ...