What is the best way to concatenate a variable name with scope in AngularJS?

Here is the code snippet I am working with:

angular.module('ExampleApp', ['ngDraggable']).
      controller('MainCtrl', function ($scope) {
        $scope.centerAnchor = true;
        $scope.toggleCenterAnchor = function () {$scope.centerAnchor = !$scope.centerAnchor}
        $scope.draggableObjects = [{name:'subject1'}, {name:'subject2'}, {name:'subject3'}];
        $scope.droppedObjects1 = [];
        $scope.droppedObjects2 = [];
        $scope.onDropComplete1=function(data,evt,i){
            var index = $scope.droppedObjects1.indexOf(data);
            if (index == -1)
            $scope.droppedObjects1.push(data);
        }
        $scope.onDragSuccess1=function(data,evt){
            console.log("133","$scope","onDragSuccess1", "", evt);
            var index = $scope.droppedObjects1.indexOf(data);
            if (index > -1) {
                $scope.droppedObjects1.splice(index, 1);
            }
        }
        var inArray = function(array, obj) {
            var index = array.indexOf(obj);
        }
      });

I need to pass variable "i" into a function call and use it in this way:

var index = $scope.droppedObjects+i.indexOf(data);
. How can I achieve this?

Answer №1

Give it a shot

let position = $scope["droppedItems"+i].indexOf(data);

Answer №2

Have you considered implementing this concept? It may offer some assistance.

let i = 0;
let the_string = 'droppedObjects' + i;

// Retrieve the model //
let model = $parse(the_string);

// Set a value to it //
model.assign($scope, 42);

console.log($scope.droppedObjects0);

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

"Every time an Ajax call is successful, the 'else' clause in

When it comes to using Ajax for user login in the system, I encountered an issue where the Ajax success function would always run the else statement even if the server returned a true Boolean value. This meant that even when the login credentials were vali ...

Ensure that the response interceptor is executed only once, even when multiple API calls are

I currently have an interceptor set up as follows axios.interceptors.response.use(undefined, err=> { const error = err.response; console.log(error); if (error.status===401 && error.config && !error.config.__isRetryRequest) { ...

In the world of React-Three-Fiber and ThreeJS, the sprite alpha can often appear quite jagged

Currently, I am tackling a project for a client and encountering an issue with transparent logos in threejs. When utilized in the application, these logos exhibit an unattractive dark border that does not align with our desired aesthetic. Despite several a ...

Having trouble getting CSS animations to work in Safari when triggered by JavaScript

By utilizing a basic CSS animation, I've managed to create a fade-in effect that relies on opacity. To kickstart the animation, I use JavaScript to ensure it waits until the browser finishes loading. While this method works seamlessly on Firefox and C ...

Having multiple instances of jQuery running concurrently on a single webpage

I am a novice when it comes to jQuery and I'm facing some issues with it. I have a basic slideshow and a weather plugin that I would like to incorporate, but strangely they both seem to malfunction when used together. <script src="js/jquery.js"> ...

Can an uploaded video file have frames and audio stripped using JS since iPhone doesn't allow inline video playback?

Summary Can JavaScript be used to extract frames and audio data from an uploaded video for streaming to a custom canvas or audio player? What are the possibilities and limitations of this approach? While I have not personally attempted to manipulate raw ...

Why is the AngularJS $http get callback not triggering when receiving status code 401?

Whenever I visit a products page, I trigger a specific service: app.factory('ProductService',['$http','$location',function($http,$location){ var factory = {}; factory.getAll = function(){ $http.get('/prod ...

I'm facing a challenge with displaying data on a dynamically created table using VueJS

I'm having an issue with dynamically generating a table using VueJS. The problem arises when creating the <th> elements. In order to set them up, I have a Vue component that is called by the addRow function. This component uses templates with v ...

Leveraging $scope.variable in Multiple Controllers in Angular JS

I'm facing an issue with my counter ($scope.counter) that I'm increment on ng-click. The challenge I'm encountering is that I want to increment it from two different controllers while keeping the counter value in sync. controllerA.js .cont ...

Tips for preventing duplicate meta tags on your website

Currently working on my website utilizing next.js. A Question for Help The code snippet below can be found in the _document.js Head component. These meta tags are considered the root level. <meta name="description" content="~~~"/&g ...

Eliminate multiple elements from an array based on their index positions, and then save the

What is the most efficient way to remove multiple items by index and save them in arrays actives and availables? I need to move selected elements from a ListBox, represented as selectedValues = [1, 4, 2]. Here's my proposed solution: var actives = ...

JavaScript encountered an issue while parsing XML: the format is not well-formed

I keep seeing an error message saying "Error parsing XML: not well-formed" when I encounter this line in my javascript code: for (var i=1; i<=totalImgs; i++) If I remove the < character from the line, the parsing error goes away. However, the javas ...

I want to retrieve a complete HTML page using an AJAX request

I am trying to retrieve the content of a specific page, but encountering issues when using this function: function getResult() { var url="http://service.semanticproxy.com/processurl/ftfu27m3k66dvc3r43bzfneh/html/http://www.smallbiztechnology.c ...

Challenges with adjusting the value of HTML range inputs

Within my HTML, I have incorporated the following three elements: <button id="left" >Previous</button> <input id="animSlider" type="range" min="0" max="0" step="1" value="0" /> //THE MAX VALUE IS SET DYNAMICALLY UPON PAGE LOAD, NOT AS ZE ...

Angulajrs - instructions for activating Bootstrap tabs

I'm trying to set the first tab as active in my modal every time it is opened. The issue I'm facing is that if I switch to the second tab, close the modal, and reopen it, the second tab remains active. How can I ensure that the first tab is alway ...

Using an object does not result in updated data, while data changes are typically observed when using a variable

In the process of developing a function to update a custom checkbox upon clicking (without resorting to using the native checkbox for specific reasons). Here's the code snippet for the checkbox: <div class="tick-box" :class="{ tick: isTicked }" @ ...

Learn how to use JavaScript to copy just one specific DIV from a group of divs to the clipboard

Is there a way to copy text from multiple divs into the clipboard? Currently, I am only able to copy one piece of data at a time. <div id="div1">Text To Copy</div> <div id="div2">Text To Copy</div> <div id=&q ...

The addEventListener feature in Bootstrap 5.2.3 seems to be malfunctioning

I have a sample page with a Bootstrap dialog being returned from the server. I want to display it inside a DIV. However, when clicked, I receive this error: Uncaught TypeError: myModal.addEventListener is not a function It points to this line of code: ...

Modifying the value of an item within a two-dimensional array

I've encountered a perplexing issue while working with a two-dimensional array named "grid" that holds objects known as "squares". In this scenario, each square simply keeps track of how many times it has been selected (clicked). After initializing t ...

How to send a server-side type to an ASP.NET webform to be consumed by JavaScript

Currently, I am working on passing a predefined Type (List) to an asp.net web form that needs to be recognized by JavaScript when the page loads. The sample data I am generating appears like this: protected List<MapCoords> createCoordinateList() ...