Angular - Strip all tags from inputs - angularjs

In my Angular app, I want to sanitise any inputs to strip any/all tags, so even if a user entered <h1>superman</h1> the html tags would be stripped.
Now I've read about ngSanitize however on this docs page https://docs.angularjs.org/api/ngSanitize/service/$sanitize it mentions whitelist, so I presume that means Angular would accept things like <h1>.
Is my understanding in this correct?
And if so, how do i forcefully remove any and all tags from any input?
Thanks.

ngSanitize simply makes html safe, so it can't run javascript inside. You'd probably want to use the simple javascript replace method with a regex here.
something like:
var str = '<h1>superman</h1>';
str.replace(/<[^>]+>/g, '');
This would remove any XML tags, not just html.

please refer to this plnkr example
https://plnkr.co/edit/F9K3sekUQUJPBUts8Jdw?p=preview
var strip = function() {
var tmp = document.createElement("DIV");
tmp.innerHTML = $scope.strip; // assuming text box is using "strip" for ng-model
return tmp.textContent || tmp.innerText || "";
};
It can be done with simple Javascript. No need for ngSanitize or any other angularjs specific code.

Related

How to use Lodash _.template in AngularJS

Could you explain me how to use Lodash _.template in order to get some value from script to .html file via {{data}} ?
For example:
In script.js I set some changes to my data object and in view.html. I want to get changed data with {{data}}
How to use lodash _.template() for this issue?
The lodash template function does not allow you to build templates from files (but you could do it when combined with Webpack). It has absolutely nothing to do with AngularJS templates. However in some situations it makes sense of using inside of AngularJS, like for example building a list of strings with a pattern or the like.
You compile a template string to a function you can call as often as you like with the values:
const executor = _.template("Hello <%= name %>, my old friend!");
console.log(executor({name: 'Alice'})); // Hello Alice, my old friend!
console.log(executor({name: 'Bob'})); // Hello Bob, my old friend!
You can also use conditional, loops, etc.: https://lodash.com/docs/4.17.15#template

Accepting html safely in angularjs

I need to accept html input (template) from user. I need to then compile it using angular's $interpolate function.
So when I get the html from user, I do this.
let $interpolate = this.$injector.get('$interpolate');
let $sanitize = this.$injector.get('$sanitize');
let html = $sanitize(toReturnStyles.cellTemplate);
el = $interpolate(html)(params);
Then I checked adding , I am good, alert didn't work.
But then I put following code in the inputbox and I saw alerts.
{{constructor.constructor('alert(1)')()}}
Please help me implement this usecase correctly.

Replacing static text content inside ngrepeat with ngclick directive in AngularJS

I've tried so many different things here with no luck. Basically i have an array of strings (just sentences). I need to ngRepeat over those and output them. No problem. But I need to be able to do a find and replace for a particular word combination ("social security" in this case), wrap it inside a link and add an ngClick directive to that link.
I'm pretty certain that i need to use a directive and this has something to do with compiling and linking. But Thats about as far as i can get with this. Any help would be most appreciated.
I think you could use something like this : http://jsfiddle.net/DotDotDot/Z9CHL/2/
I'm not sure it's the best implementation, but at least it works
The HTML code is quite simple, I send the custom directive one parameter, the full sentence
<ul ng-repeat='sentence in list'>
<li><span the-dir txt="sentence"></span></li>
</ul>
On the javascript side, it's quite easy but longer :
.directive('theDir', function($compile){
var r=/(social security)/ig;
return {
scope:{txt:'='},
link:function(scope,element,attributes){
scope.aFunction=function(){
console.log('In the directive, you clicked on social security');
}
if(r.test(scope.txt)) {
splitted=scope.txt.split(r);
console.log(splitted)
var newSpan=new angular.element('<span>');
for(var i=0;i<splitted.length;i++)
{
if(r.test(splitted[i])){
var newLink=new angular.element('<a>');
newLink.attr('ng-click','aFunction()');
newLink.addClass('social-security');
newLink.html(splitted[i]);
newSpan.append(newLink);
}
else
newSpan.append(splitted[i]);
}
element.append(newSpan);
$compile(newSpan)(scope);
}
else
{
element.html(scope.txt);
}
}
}
});
I use a Regular Expression to find all occurrences of your sentence 'social security', split the full sentence on these occurences, then replace each time the words by a new angular.element (an HTML link in this case, with a ng-click attribute). I append all the regular words and the links to the original element, and then $compile the newly created span with the working links in order to have a working ng-click.
And it seems to work
I let you dig in the code, and I hope it helps you
Have fun

Sanitize string to using angularjs

I basically want to use tel tag to make a phone call.
<a class="callButton" href="tel: {{phoneno}}"></a>
I am using $compileProvider to remove unsafe tag which comes by default, It works perfectly fine post 1.0.4v of angularjs. However below this version it doesnt work. Can anyone suggest how to implement this feature using angular version 1.0.4 or below?
Here is the sanitizing code which I am using in js file
app.config(['$compileProvider', function ($compileProvider) {
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
}
Assume I have already defined app variable.
P.S. This is an enhancement for particular app which basically works below 1.0.4v
Thanks
Add this to your scripts after angular is loaded.
I asume your on 1.1.5, but change to whatever you need the version to be.
http://code.angularjs.org/1.1.5/angular-sanitize.min.js
Example:
sanitizeSomething = function(string) {
return $sanitize(string);
};
sanitizedString = sanitizeSomething(string);

AngularJS - augmenting dynamic HTML content with user-generated content

I'm new to AngularJS and hoping someone can help me get my head round this please!
I'm developing a web e-reader that pulls in pages of HTML content dynamically. So far, I'm doing that with an $http AJAX call and binding it in with 'ng-bind-html-unsafe' (the HTML is our own, simply served from a directory on the same server. I have control over the HTML so I could do this differently if needs be). So each time the user presses previous/next, the controller simply fetches in the previous/next page of HTML and switches that in the model - that works great.
But next I need to augment this dynamic HTML with user additions, e.g. comments and highlights. They need to appear where the user adds them, e.g. a comment would most likely sit underneath a particular paragraph.
With JQuery I guess I would give each of the HTML elements its own ID and associate each bit of user-generated content with a particular ID. Then I could manipulate the DOM myself, for example adding each comment under its associated element.
What's the right approach with AngularJS, since the principle seems to be to avoid direct DOM manipulation altogether?
I could see how it could be done by defining the HTML content as separate elements in the model, having individual JavaScript objects for each paragraph, header, image, etc. But that would basically be defining DOM-like data in JavaScript - and that feels quite wrong and messy...
Use an "ng-include" and dynamically bind a src attribute from the controller. Adding dynamic, user generated content is as adding the binding variables to your html. Following is angular code that implements previous/next buttons that dynamically loads html templates and populates them with the user added comments. At the bottom is a link to a fully functional jsfiddle.
angular.module('app',[]).controller('controller', function($scope){
var change;
change = function(){
$scope.src = $scope.page + '.html';
};
$scope.page = 1;
$scope.items = [];
change();
$scope.submit = function(text){
$scope.items.push(text);
};
$scope.next = function () {
if($scope.page < 3){
$scope.page++;
change();
}
};
$scope.previous = function () {
if($scope.page > 1){
$scope.page--;
change();
}
};
});
http://jsfiddle.net/jwanga/rnL7c/

Resources