How to securely utilize eval() with $scope within Angular applications

Are there security risks involved in this code? Could it be vulnerable to code injections?

$scope.placeholder = function(value, def) {
    var val = eval("$rootScope.master.user." + value);
    if (val) {
        return val;
    } else {
        return def;
    }
};

Initially, I used bracket notation. However, I discovered a limitation when passing an object like Address.addr1 as shown in the example below:

<input type="email" ng-model="user.email"  placeholder="{{placeholder('email', 'Email...')}}" /><br/>
<input type="text" ng-model="user.Address.addr1"  placeholder="{{placeholder('Address.addr1', 'Addr. Line 1...')}}" />

I hoped the following link might address my concerns, but I still had doubts: Is using javascript eval() safe for simple calculations in inputs?

Answer №1

Is there a specific rationale behind why you are unable to complete this task? Your query seems to hint at the XY problem, as pointed out by Claies:

<input type="email" ng-model="user.email"  
       placeholder="{{ user.email || 'Email...'}}" /><br/>
<input type="text" ng-model="user.Address.addr1"  
        placeholder="{{ user.Address.addr1 || 'Addr. Line 1...'}}" />

Alternatively, it begs the question of why you feel compelled to tackle this issue in the first place. A placeholder serves a purpose only when the field is empty, so a fixed value would suffice:

<input type="email" ng-model="user.email" placeholder="Email..." /><br/>
<input type="text" ng-model="user.Address.addr1" placeholder="Addr. Line 1..." />

Answer №2

To access properties of an object in JavaScript, you can utilize Bracket notation which is a safer alternative than using eval.

var value = $rootScope.master.user[value];

Avoid using eval in your codebase as it poses security risks. To learn more about why using the JavaScript eval function is discouraged, check out this resource.

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

Is it advisable to utilize $timeout in AngularJS for executing a function after ng-repeat has completed?

Currently, I am utilizing the ngRepeat directive to display a large data list. In order to execute a function after the completion of the ng-repeat, I have incorporated the use of the $timeout. While this approach is functioning effectively, my concern is ...

How to retrieve the row index from a table using JavaScript

This question has cropped up numerous times, and despite trying various solutions suggested before, none of them seem to be effective in my case. Within a modal, I have a table where users can make changes that are then used to update the database. The ta ...

Upgrade your AngularJS Directive to an Angular 2.x+ Directive by using an HTML decorator

Is it no longer possible to utilize Angular directives as what I like to refer to as "HTML decorators"? I found this method extremely useful in Angular 1.x when transitioning legacy applications to Single Page Apps by creating a set of directives to enhan ...

JavaScript or Query: Transforming an Object from an Associative Array

Can someone help me out with converting an associative array into an object in JavaScript? I tried searching on Stackoverflow but couldn't find a working example. Here is the example structure: var combinedproducts = [["Testing-1","test-1"],["Testin ...

Loading necessary CSS when needed in React JS

I am currently in the process of converting a bootstrap template to react framework. My question is, is there a way for me to load stylesheets on demand? For instance, if I have 2 components and I import the same stylesheet separately in both components, ...

How can one utilize Codemirror code folding while avoiding the use of "[ ]"?

I am looking forward to implementing Codemirror codefolding for folding only braces { and }, as well as comments. However, I am facing an issue where it also folds square brackets [ and ]. Since square brackets are usually part of one-line statements, I do ...

Oops! There seems to be an error in the code: SyntaxError: DOM Exception 12 setRequestHeader@[

Currently working on the development of a mobile application for Android and IOS using Phonegap, AngularJS, and CORS_REST. Most headers are functioning well on Android, but encountering issues when testing on iPhone with GapDebug. An example of the authen ...

Issues with the transmission of a PHP json_encoded 2D array to JQuery Ajax

I am faced with a challenge in creating a demonstration to retrieve data from a PHP script that executes a SQL query, converts the resulting array into JSON format, and sends it back to the jQuery AJAX caller within the PHP file. Despite my efforts, the da ...

Execute a script using an HTML button

I have a HTML button element with the following code: <a class="btn btn-sm btn-danger"><i class="ace-icon fa fa-reply"></i>Reset CM</a> Also, I have an Angular variable called "{{product.name}}". My goal is to execute the follow ...

Encountering a 'Object is not a function' issue while attempting to implement Page Object with Protractor

Whenever I attempt to run my tests, I keep encountering a TypeError: object is not a function. Prior to incorporating PageObject, everything worked fine. Below is my spec.js 'use strict'; var todoAppPage = require('../pages/angular.page&a ...

Printing the HTML Template of a widget with multiple loops results in a blank first page being displayed

I have encountered an issue while working with a table and ng-repeat loops in my report widget. The table displays fine on the screen, but when I try to print it, there is always a blank page at the beginning. Interestingly, if I remove the second and thir ...

The EventListener functions properly only when the browser window is not in focus

In my Angular application, I am using Two.js to draw an SVG image. After drawing the SVG with some elements in Two.js, I add event listeners to its elements like so: this.courtRenderer.update(); // once this command is executed, Two.js will draw the SVG f ...

Having difficulty retrieving the selected value in JSPDF

I am attempting to convert my HTML page into a PDF format by utilizing the following code: domtoimage.toPng(document.getElementById('PrintForm')) .then(function (blob) { var pdf = new jsPDF('p', &apo ...

Get rid of the data in an input file field

Incorporating an upload form/group on my page has been successful, although I have encountered a limitation in adding a reset/clear function to it. The control setup is as follows: <div id="uploadform" style="width:100%;" data-provides="fileu ...

JavaScript newbie diving into the revealing module pattern

Currently diving into Addy Osmani's fantastic read on javascript design patterns, however, I'm facing a roadblock. Can someone help me identify the issue with my approach? (I'm experimenting with Raphael for fun): var myPaper = Raphael(&apo ...

The simultaneous execution of several ajax requests is leading to jumbled data sets

I've been working on a phonegap application that utilizes jQuery Mobile for its primary structure. During the execution of the app, various ajax calls are made to fetch the latest data. For example, a list of items is fetched for the homepage, while ...

The jade files are not being detected by gulp.watch()

Out of the blue, my gulpfile.js's watch statement for all of my jade files decided to stop functioning. Any idea why this might be? The Jade task is set up as follows: gulp.task('jade', function() { gulp.src('app/*.jade') . ...

What are some strategies for ensuring that Plotly JS can adapt its height and width to fit the entire div dynamically, without relying on fixed pixel dimensions?

Is there a way to ensure that Plotly automatically adjusts to the size of the container #myDiv without any noticeable delay when the top button is clicked? This code snippet demonstrates a high delay: var z = [], steps = [], i; for (i = 0; i < 500; i+ ...

Accessing data from another domain using JavaScript with Cross-Origin Resource Sharing (

After researching various CORS and JSON request discussions, I find myself puzzled as to why the first script functions correctly while the second one does not. I am eager to enhance my understanding of CORS, Javascript, XMLHTTPRequest2, and AJAX. The fol ...

Step-by-step guide on transferring form data from an Ionic application to parse.com MBaaS through the REST API

Today is my first day with Ionic/Angular, and I'm diving in out of necessity. I've been using tutorials and documentation to create a demo/test app that submits data to the Parse.com MBaaS service. However, I seem to be stuck somewhere and clue ...