Using AngularJS's sanitize feature within the ng-model directive

Utilizing AntiXss Encoder on the server side to protect against XSS attacks, all responses include HTML unescape characters like "&lt:script&gt:alert(1);&lt:/script&gt:" (with ';' replaced as ':')

When binding, I use sanitize with ng-bind-html without any issues. However, there is another control input for update mode. Upon clicking the update icon to edit text, a textarea is displayed and the binded tag with ng-if is hidden. The textarea has an ng-model attribute. I am unable to escape HTML characters in the textarea like ng-bind-html. Here is the code snippet, please assist as I am struggling with this.

In the fiddle provided, the edit mode textarea should display "<script>alert(1);</script>" without triggering the alert action, and the data sent to the server should also display the same...

Here is the fiddle

var app = angular.module('myApp',['ngSanitize']);

app.controller('MyCtrl', function($scope, $sce, $sanitize) {
    $scope.post1 = "&lt;script&gt;alert(1);&lt;/script&gt;";
    //$scope.post2 = $sce.parseAsHtml("<h1>alert(1)</h1>");
    $scope.logs = ["log created"];
    $scope.log = function(val){
    $scope.logs.push(val);
    }
});
.label {
  text-decoration:underline;
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
      <div class="label">Edit mode :</div>
      <textarea ng-model="post1" style="width:100%;" rows="5"></textarea><br />
      <div class="label">Binding mode :</div>
      <div ng-bind-html="post1"></div><br />
      <div class="label">Data will be send to the server :</div>
      <div>{{post1}}</div><br />
      <div class="label">Logs (if needed) :</div>
      <div ng-repeat="d in logs">
        <p>{{($index+1) + ". " + d}}</p>
      </div>
</div>
</div>

Answer №1

Utilize the $sanitize service that you have, as it seems like you are not currently using it effectively. Consider modifying the following code:

$scope.post1 = "&lt;script&gt;alert(1);&lt;/script&gt;";

to something like this:

$scope.post1 = $sanitize("&lt;script&gt;alert(1);&lt;/script&gt;";)

Additionally, keep in mind that $sanitize is not included in the core Angular package. Make sure to include angular-sanitize.js and declare a dependency on the ngSanitize module if you haven't already done so:

var app = angular.module('myApp', ["ngSanitize"]);

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

What is the best way to retrieve the initial cell from a row that the user is currently hovering over?

Is there a way to extract the first cell from a row when a user hovers over it and then clicks a specific key combination? (considering using jQuery) I have a table set up similarly where placing the mouse over a tr and pressing ctrl+c will copy the ID t ...

Is it possible to utilize personalized functionalities in the main.js file of the Firefox Addon SDK?

Why am I encountering difficulties accessing custom functions with the Firefox Addon SDK? In the code snippet provided below, whenever I click on context menu Sub Item 1, it does not work as intended; It is trying to access the custom function verifyTest( ...

Replacing an Angular 2 application with a new webpage

I've been working on a project using Angular 2 and following this tutorial: Every time I run my api with npm run api on localhost:3000, the entire application gets replaced by another webpage. https://i.sstatic.net/5pIfX.png Here is my package.json ...

Encountered issue: The action dispatched by Effect "n.loadInfo$" is invalid and thus resulted in an error

I'm encountering an error while trying to write an effect for an action. The error message is: "Effect "n.loadInfo$" dispatched an invalid action: null Error" Here's my current effect implementation: @Effect() loadInfo$ = ...

Having trouble getting the node serialport module to function properly when using the child process fork()

My current project involves implementing an asynchronous read in USB using fork() from the child_process module in electron. Essentially, upon clicking a div (id="read"), a message is sent from the renderer process to the main process. The main process the ...

Platform providing video recommendations based on user preferences

Assigned with creating a unique online video lecture platform inclusive of a recommendation system for the students in my area, I have limited knowledge on html, css, java, and php as my education primarily came from YouTube tutorials. Confused about what ...

Exploring the world of functional programming within nested arrays

I have been shifting towards functional programming over imperative programming recently. Imagine I have a nested array data structure and my goal is to update the values of the innermost arrays. What approach would be most effective? Here is the imperat ...

What is the rationale behind not storing OAuth2 access tokens as HttpOnly secure cookies? How could this approach be implemented in a Node.js application?

I have a Node.js RESTful api setup where the response token received after posting to /oauth/token typically looks like this: { "refresh_token": "eyJraWQiOiI2...", "token_type": "Bearer", "access_token": "eyJraWQiOiI2Nl...", "expires_in": 3600 } ...

Utilizing Bootstrap modal to insert data into phpMyAdmin database - a comprehensive guide

I'm attempting to insert data into my localhost database using a Bootstrap modal in conjunction with Laravel 5.2. Here is the PHP function I am using: public function addReport(Request $request) { $postreport = new PostReport(); $postreport- ...

What is the best way to stop the browser from automatically redirecting to another page after submitting a form?

I am using an AJAX call to a method that returns JSON data. How can I retrieve and read the JSON response without being redirected to a new empty page? [HttpPost] public JsonResult Test() { return Json("JSON return test", JsonRequestBehavior.AllowGe ...

Utilizing JavaScript or PHP to assign a uniform class to dynamically generated elements

Hello! In my online shop, each category has a page with all subcategories and a table of products. I want each product row in the table to have the same color as its corresponding sorting button for the subcategory. This must be done dynamically as I hav ...

Incorporating Paged.JS functionality into a React/JS web application

My attempt to showcase my html page using paged.js in a react project has hit a snag. The html loads perfectly when accessed from local host (not via npm start, but the live server extension on vscode). However, following the steps outlined on this website ...

Passing Selectize.js load callback to a custom function

I set up selectize.js to gather configuration options from html data attributes. One of the configurations involves specifying a js function for custom data loading (not just simple ajax loading). Everything was working smoothly until I tried running an as ...

switch between showing and hiding dynamic table rows

As I dynamically add rows to a table, each row can either be a parent row or a child row. My goal is to toggle the visibility of child rows when the parent row is clicked. if (response != null && response != "") { ...

Utilize SectionList and a custom header view on Y to achieve a translation effect that creates a visually appealing empty space as

Hello everyone, I am fairly new to React Native and the Animated API. My goal is to create a simple parallax header and an Animated SectionList similar to this demonstration. https://i.stack.imgur.com/R2GBP.gif Below is a snippet of my code: export defa ...

Tips for optimizing scrolling of a specific element with a letter parameter

For my web application project, I am trying to implement a feature where clicking on a letter will scroll to display the relevant content. Below is the JavaScript code snippet: <script> import Bscroll from 'better-scroll' export default ...

What is the best way to retrieve the variable value following the $getJSON method call?

Within the following code snippet, I have a function called counter that increments a global variable. This function is used to count elements within a JSON file. My query pertains to retrieving the value of the counter after the $getJSON call. I am puzzle ...

Tips for utilizing variables as the initial value of a JSON Object

Here is a JSON configuration example: { "Users" : { "182723618273612" : 15, "AddedUser" : 1 } } I have generated this field using a JavaScript function, but now I want to change the name of "AddedUser" ...

Converting a Backbone collection with attributes into a JSON format

Can you provide guidance on serializing a Backbone collection with attributes and models into JSON? For example, consider the following collection: var myCollection = Backbone.Collection.extend({ initialize: function (attr, options) { this.prop ...

Incorporating a JavaScript variable into an inline HTML onclick event

Having trouble passing a variable into an inline onclick function. I've tried researching and following suggestions from this link, but encountered errors (Uncaught SyntaxError: missing ) after argument list): pass string parameter in an onclick func ...