Combining strings in a loop with Angular's $scope

I have four values with the following names :

$scope.restaurant.restaurantIsTop
$scope.restaurant.restaurantIsRecommended
$scope.restaurant.restaurantIsNew 
$scope.restaurant.restaurantIsPromoted

Each of these values can be either 0 or 1. My goal is to check each value and if it is equal to 1, change it to true, otherwise set it to false.

Manually checking each variable can be done, but it is not the most efficient way, especially for multiple values. As a solution, I have created an array :

var varietyArray = ["restaurantIsTop" ,
                                "restaurantIsRecommended",
                                "restaurantIsNew",
                                "restaurantIsPromoted"

            ];

        angular.forEach (varietyArray, function (val) {

            console.log($scope.restaurant.val);
        })

I want to check all four variables in the loop above. Any suggestions?

EDITED :

I want to display these values in Angular Material checkboxes :

                    <div class="col-sm-12">
                            <div class="md-form-group">
                                <md-checkbox ng-model="restaurant.restaurantIsTop ">
                                    best
                                </md-checkbox>
                                <md-checkbox ng-model="restaurant.restaurantIsRecommended">
                                    suggested
                                </md-checkbox>
                                <md-checkbox ng-model="restaurant.restaurantIsNew">
                                    new
                                </md-checkbox>
                                <md-checkbox ng-model="restaurant.restaurantIsPromoted">
                                    promote
                                </md-checkbox>
                            </div>
                    </div>

Answer №1

If you want to check a variable within a loop and set it conditionally, you can do it like this:

var $scope = {
  restaurantIsTop: 1,
  restaurantIsRecommended: 0,
  restaurantIsNew: 0,
  restaurantIsPromoted: 1
};

var varietyArray = ["restaurantIsTop" ,
                            "restaurantIsRecommended",
                            "restaurantIsNew",
                            "restaurantIsPromoted"

        ];

angular.forEach(varietyArray, function (val) {

  $scope[val] = ($scope[val]) ? false : true;
  console.debug($scope[val]);
})

To access the scope variable, use $scope[VariablenameAsString]

jsfiddle

Answer №2

Like mentioned before, there's no need to modify the values of those properties. A value of 0 equals false, while a value of 1 equals true.

When it comes to the Material checkbox, it will interpret these values as either "falsy" or "truthy," so when displaying the data through the checkboxes, you should be good to go.

Just bear in mind that the checkboxes will update the model with proper boolean values, which could result in a mix of 0, 1, true, or false.

Hopefully, this information is helpful to you!

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

Having Trouble with QR Code Generator Functionality

UPDATE: The initial code has been updated to implement the recommendations provided. I am currently working on a QR Code generator that updates every minute. Although I have developed the code below, I am encountering some errors and could use some assist ...

Utilize the require node module to access and read JSON files within a specific folder

I'm currently working on a project where I need to read multiple JSON files using a loop in my application. The code snippet below shows how I successfully read a single file: const translations = require("../data/hello" + fileEndWith); However, th ...

Guide on converting a GraphQL request string into an object

Seeking assistance with intercepting and parsing GraphQL queries/mutations from a POST request body in an Apollo lambda server environment running on Node.js. The requests do not come in JSON format, but as GraphQL query language. I have been unable to fi ...

Is there a way to use jQuery to hide rows in a data table that contain a specific code, such as "1.1" or "1.2," that includes a

When using ajax, I pass data from two inputs to another page. These values are then used in a query to display the results in a data table on the main page within the success function. Now, I'm looking to implement a condition where any data containi ...

What is the process for submitting a record to a table following the activation of a JavaScript link or button

I am working on creating a like-unlike button below each post for registered users to interact with. I have successfully created the button itself, but now I need to figure out how to store records when a user clicks the button. My idea is to utilize a tab ...

Issue with Bootstrap checkbox/switch

Trying to determine the status of a checkbox - whether it's checked or not. The default state is unchecked, but I need to perform actions when it is checked and also when it gets unchecked. Currently using bootstrap 5.3.0 alpha html <div clas ...

Struggling with Getting My Animation to Function Correctly

I am trying to create a JQuery Animation that will move a div covering a text box up into the border when clicked. Despite multiple attempts, I can't seem to get the animation to work properly. Any suggestions? JavaScript function moveup(title,text ...

Learn the art of generating multiple dynamic functions with return values and executing them concurrently

I am currently working on a project where I need to dynamically create multiple functions and run them in parallel. My starting point is an array that contains several strings, each of which will be used as input for the functions. The number of functions ...

The destroy method of Chart.js does not appear to have any impact on the

Hello, I've come across this issue in my react app that I need help with: this.chart = new Chart(node, options); // adding data to the chart ... this.chart.destroy(); this.chart = null; this.chart = new Chart(node, options); // adding data to the cha ...

What is the method to trigger the jQuery 'mouseenter' event on an element using Selenium?

Struggling to automate a scenario using selenium where I need to click on a menu element. I've tried various methods, except jQuery. WebDriver normal click and JavaScript click() haven't worked. Can someone assist me with implementing jQuery in s ...

The GET request for a "places" endpoint in a node js application is experiencing issues

Today marks my second day working with node js and mongo. I've explored different tutorials and currently, I'm attempting to follow this specific one: https://github.com/amejiarosario/todoAPIjs/commit/d3be6a287e8aff39ab862971da4f050d04e552a ...

issue with the emit() and on() functions

While diving into my study of nodejs, I encountered a puzzling issue where emit() and on() were not recognized as functions. Let's take a look at my emitter.js file function Emitter(){ this.events = {}; } Emitter.prototype.on = function(ty ...

Encountered a 404 error when attempting to deploy create-react-app due to failed resource loading

Any assistance would be greatly appreciated. Thank you! Although my website runs smoothly locally, I am encountering issues when trying to deploy it in a production environment. Upon executing npm run deploy, the expected outcome is an automatic build for ...

Exploring TypeScript integration with Google Adsense featuring a personalized user interface

After following a tutorial on implementing Google AdSense in my Angular App, I successfully integrated it. Here's what I did: In the index.html file: <!-- Global site tag (gtag.js) - Google Analytics --> <script> (function(i,s,o,g,r,a,m ...

What is the best way to adjust a CSS width using the output from a JavaScript function?

I am facing a challenge with a GridView within a div wrapper. The row headers along the left side need to always be visible. So far, this setup is working fine. However, I need the wrapper to have a variable width to adjust to the browser size. Although I ...

Angular JS is experiencing issues with two modules not functioning properly on a single page

Angular JS is a new technology for me. I have two modules, first2a and first22. Each module contains a controller named model1 and model2. Here is the HTML code: <!DOCTYPE html> <html > <head> <link rel="icon" ...

Unusual shift in behavior - <input> on Windows 8.1

Our application is a unique HTML5/WinJS Google Talk app tailored for Windows 8 users. Within our app, we utilize a textarea for chat input with a predefined maximum height. We have coded the height to automatically adjust to the maximum limit once reached. ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

Navigate to the grandchild state with a specific parameter using ui-router's sref in the

Is there a way to create a sref that will navigate me to a grandchild state while also having a URL parameter for the child state? Check out this pseudo code example: .state( 'foo', {url:'/', template:'<div ui-view></div ...

What is the best way to update the content of a particular div and its associated link ID whenever the link is clicked?

I need to update the content of a div by clicking on an href link that includes an id named data. The issue I'm facing is that I can't access the id value within my script because it's passed within a function. How can I pass the data variab ...