Exploring Variable Naming in Angular with Dynamic Scope

Is there a way to avoid using large IF statements in my controller when working with fields/models that have similar logic but different scope variable names? I'm looking for a solution to dynamically append numbers to the scope variable names in Angular, instead of having $scope.search1 and $scope.search2. Is this feasible?

For instance, can I achieve something like $scope.search + id rather than hardcoding each scope variable name? How would I go about implementing this in Angular?

In my controller:

$scope.getresults= function() {
    if ($scope.search1) {
        $http.jsonp('http://api.com/', {
        params: {
            query: $scope.search1
        }
    if ($scope.search2) {
        $http.jsonp('http://api.com/', {
        params: {
            query: $scope.search2
        }}}

I'd prefer to do something like:

$scope.getresults= function(param) {

        $http.jsonp('http://api.com/', {
        params: {
            query: $scope.search + param
        }}

Unfortunately, this approach does not work as intended. Any assistance on how to address this issue would be greatly appreciated.

Answer №1

One can access properties inside an object in JavaScript in two ways: using Dot Notation (object.key) or bracket notation object['key']. In the latter way, one can use expressions or dynamic variable names like object[expression]. Since $scope is a JavaScript Object, it is recommended to utilize bracket notation for accessing the scope with the dynamic value being passed, as demonstrated below:

$scope.getresults= function(param) {

        $http.jsonp('http://api.com/', {
        params: {
            query: $scope['search' + param]
        }}

Answer №2

One way to access object properties is by using object notation.

$scope['search' + param]

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

Transitioning to abstract states in AngularJS involves moving to a higher

I am currently developing an AngularJS application that consists of two main states: Introduction wizard for the app App pages with a Navigation template and nested views The goal is to default to State 1 when someone first accesses the app, then procee ...

Converting milliseconds into a date format

I am looking to change milliseconds into a string that displays the time duration. function convertMsToTime(ms) { return ('' + Math.floor(ms / 86400000) + 'd -' + Math.floor((ms % 10) / 60).toString().padStart(2, '0')); } ...

The React Component is limited to updating once

Exploring the React Native code below: import React from 'react'; import {Text, View, StyleSheet, Button} from 'react-native'; export default class Target extends React.Component { constructor(props){ super(props); ...

When a JavaScript click event is triggered, IE8 can reset certain margins to zero

I am experiencing an issue with 3 divs containing content that becomes visible when clicking on 3 buttons. You can see a demonstration of the problem here: At times, when I click one of the buttons, the layout seems to be disrupted as shown here: It appe ...

Launching email client with predefined content using React Native

I'm currently utilizing an npm package for launching a mail client along with specific data. You can find the package here: https://www.npmjs.com/package/react-native-mail-compose Furthermore, I am following their provided example: import MailCompos ...

Is there a way to retrieve the final elements from a deeply nested array?

I've been struggling to extract the last item from a nested array of objects. I've tried using methods like flatMap, flat, filter, and splice, but so far haven't had any luck getting the desired array. const array = [ [ { total_c ...

What is the best way to properly pass parameters?

const root = { user: (id) => { console.log("returning object " + JSON.stringify(id.id) + " " + JSON.stringify(storage.select("users", id.id))) return storage.select("users", id.id) } } Struggling to correctly pass the parameter ...

What are the advantages of using HttpClient compared to fetch?

With the introduction of Angular 2+, HttpClient now facilitates HTTP requests sent down an RxJS observable. I'm curious about why one would opt for using HttpClient's API instead of the standard fetch for individual HTTP requests. I have a good ...

Determine whether the user has scrolled past a specific threshold

Is there a way to display the button with the id backtotop only when the user has scrolled more than 250 pixels? This is my code: <template> <div> <button v-if="checkScroll" class="goTop" @click="backToT ...

Switching the default image using jQuery upon click event

When I click on the image, I want to see a new image appear for just one second before returning to the default. I tried using setTimeout() function, but even after one second, I still see the same pressed.svg image. Here is my complete code: <html> ...

Using AJAX to dynamically edit and update PHP data

The information displayed on my index.php page is fetched from a database using the mysqli_fetch_array function. The data is presented in a table format with fields like Name, Age, Email, and Update. An edit button allows users to modify the data. Here is ...

Validating File Names with Formik and Yup

I'm currently implementing file name validations using YUP with regex. I keep encountering an error whenever a file is uploaded; the file name must not begin with special characters. For more details, please check out the codesandbox link: Code Link a ...

I'm looking for the specific jQuery/JavaScript function that will accomplish this task

let data = [{ name: "abcd", type: "1 kg" }, { name: "efgh", type: "1 cai" }, { name: "ijkl", type: "1 kg" }]; If I have the name, I would like to get the corresponding type. For example, if I call getType('abcd'), it sho ...

Utilizing ng-model and ng-repeat in AngularJS to populate models with a list of objects

I need to call a POST function, and I have to compress the data in a web form into an object beforehand. I utilized ng-repeat to showcase all inputted data and initialized this value for input, but I am unsure how to utilize ng-model to store the data. I c ...

Organize chat messages based on date using JavaScript

I came across a similar query, but it didn't resolve my issue. Check this out: How can I group items in an array based on date? My goal is to organize these chat messages by date after fetching them from the database using AJAX. The console displays ...

Alert: Route.get() is requesting a callback function, but is receiving an [object Undefined] while attempting multiple exports

I'm attempting to export the middleware function so that it can be called by other classes. I tried searching on Google, but couldn't find a solution that worked for my situation. Below is the code snippet: auth.js isLoggedIn = (req, res, nex ...

Accessing a hyperlink in an alternative browser

Is there a way to transfer a link from one browser to another? For example, moving a link from Firefox to Chrome or from a Chrome Incognito window to a regular Chrome window. Let me provide more context. I have a webpage that refreshes every second and us ...

What is the process for reverting variables back to their original values using pure Javascript?

I am working on developing a hangman game using vanilla javascript and I need some assistance with resetting the game after a player loses. Specifically, I would like to: 1. Reset the "guessRemain" variable. 2. Clear out the "guess" id so that none of the ...

Is the eval() function initially used to directly translate the evaluated string?

Try running this code snippet in your browser: eval("(function() { console.log(JSON.parse('" + JSON.stringify('THIS IS COOL') + "')); })()"); It will output THIS IS COOL, however, if you run the following: eval("(function() { console ...

How should a request from express/connect middleware be properly terminated?

If I have middleware like the following; var express = require('express'); var app = express(); app.use(function (req, res, next) { var host = "example.com"; if (req.host !== host) { res.redirect(301, host + req.originalUrl); ...