I'm trying to sanitize HTML in the controller as I'm trying to update the document.title dynamically with the title of the post. (I know that for SEO purposes this isn't recommended but I need to use it here)
$scope.prevTitle = "dynamic title gets pulled in here &"
document.title = $scope.prevTitle
For this example, I've just used a random HTML entity. I've tried the parseAsHtml method from the official documentation but I'm having no luck. I tried the following:
document.title = $sce.parseAsHtml($scope.prevTitle)
But no luck. The documentation suggests it needs to be used within a function. Any suggestions on how I would acheive this?
A console log of the above ( console.log($sce.parseAsHtml($scope.prevTitle)) ) would return:
function (b,c){return e.getTrusted(a,d(b,c))}
$sanitize can be used as #acg pointed out. Alternatively, you can use it directly with the ng-bind-html directive where it automatically sanitizes the output variable before rendering the output.
The above point is not quite clear in the documentation, but there is a fairly extensive example in it with which you can play in pluncker.
Please also bear in mind that ngSanitize is an external module and you need to explicitly load angular-sanitize.js or include it in your js minification.
Use $sanitise and trustAsHtml instead
First of all inject 'ngSanitize' in your module
Now in your controller, just add
$scope.prevTitle = "dynamic title gets pulled in here &"
document.title = $sce.trustAsHtml($scope.prevTitle)
If you want to sanitize the html returned, I would think it would be as simple as using the $sanitize service:
document.title = $sanitize($sce.parseAsHtml($scope.prevTitle))
Related
I am working on enhancing a feature of an already deployed application. All the js code is minified and i only can excess html files. I need to call a function on-click of a 'div' which parse some elements and open a new tab with resolved url(url updated with help of parsed elements).
My initial thought is to make a function in a new js file and add link to it on main html page. Evidently the call to function is fine with on click attribute call on the div. But while passing the angular controller parameters it throws error -
<div onclick="jumpToPage({{vm.username}})"></div>
function jumpToPage(user){
console.log(user);
};
Note - I don't have access to update minified files and i know i can un-minified it but there are lot of files and process is too long.
Please let me know how to resolve/pass parameter to JavaScript function
It should be onclick="jumpToPage(vm.username)">
If you pass {{vm.username}} it will get evaluted.
e.g. vm.username ="some_name"
so,your controller will get some_name and not referance to vm.username
and
it try to search for the same refarance.If it not find then throw exception.
try to use ng-click, when we use ng-click we don't need to use {{}} anymore, since it is automatically bind the model.
My problem is passing Map object from grails controller to JavaScript.
I have the following code inside controller
def scoreValue=new HashMap<String,String>();
scoreValue.put("0","poor");
scoreValue.put("1","good");
...
return (view:'viewname',model:[scoreValue:scoreValue]);
I have been searching for solution and have got this link pass a groovy array to javascript code. but could not help.
What I did was change the return statement to
return (view:'viewname',model:[scoreValue:scoreValue as grails.converters.JSON])
and inside gsp view I have the following code.
<g:if test="${scoreValue}">
var scoreValue=${scoreValue};
</g:if>
But what i got inside html page is the following
var scoreValue={"0":"Failure","1":"Poor"}
any help would be appreciated. thanks!
There's actually a few ways of handling GSP encoding. In addition to D. Kossatz's answer, these methods will help you out (see more at mrhaki's excellent Grails Goodness blog)
var scoreValue=${raw(scoreValue)};
var scoreValue=${scoreValue.encodeAsRaw()}
Please be aware that there is an inherent risk of cross-site scripting vulnerabilities when rendering user input unprotected on the page. So long as you know for certain that only you can set that value, and proper safe-checks to ensure it is what it is supposed to be, you should be fine.
Try:
var scoreValue= <g:applyCodec encodeAs="none">${scoreValue}</g:applyCodec>;
I am trying to bind the following json response in my html page.
The json is as follows:
{
"key":{
"text":"<p>For more information, please visit Support .</p>"
}
}
html page
<div ng-bind-html="message"></div>
Controller Code
$http({
method: 'GET',
url:'DAYS.json'
}).success(function(responsedata) {
$scope.message=responsedata.key.text;
}).error(function(responsedata){});
customizeWindow function inside controller
$scope.customizeWindow = function(url) {
window.open(url, "_blank", "toolbar=yes, scrollbars=yes, resizable=yes,top=70, left=190, width=970, height=460");
}
The ng-bind-html binds the html tags but it strips off the javascript and ng-click event.
i get only Support when i inspect element and the link does not work.
Please suggest me a solution.
This happens since angular Automatically uses $sce -> Strict Contextual Escaping. it allows you to ng-bind-html but it doesn't allow you to add possibly malicious code like JS.
What you are after is explicitly trusting that segment as HTML.
therefore:
angular.module('app', ["ngSanitize"]) // You have to include ngSanitize or it wouldn't work.
.controller('Ctrl', function ($scope, $sce){
$scope.htmlData = <p>For more information, please visit Support .</p> //Took from your example.
$scope.$watch("htmlData", function(newValue){
$scope.trustedData = $sce.trustAsHtml(newValuew);
});
});
HTML Usage:
<p ng-bind-html="trustedData"></p>
Angular Resource:
Strict Contextual Escaping (SCE) is a mode in which AngularJS requires
bindings in certain contexts to result in a value that is marked as
safe to use for that context. One example of such a context is binding
arbitrary html controlled by the user via ng-bind-html. We refer to
these contexts as privileged or SCE contexts.
As of version 1.2, Angular ships with SCE enabled by default.
read on : Angular on SCE - trustAsHtml method
ng-bind-html content is sanitized by default and its not meant to bring DOM into the page. You would use this method to bring content onto the page. Eg if you have a rich text editor - you want to feed it html content, however sanitized and thats when you use ng-bind-html.
For your purpose I would suggest to use templates or plain model binding.
Source of your json, what ever that is should not really know anything about the consumer side (your page) implementation/technology what if you move away from angularJS and start using Knockout, you will have to change server-side as well, because Knockout will have no idea about ng-click. Just pass back the content like http://www.google.com, 'For more information, please visit' and bind it.
{
"key":{
"textsource": {
source : 'http://www.google.com',
message : 'For more information, please visit '
}
}
}
<p>{{textsource.message}}<div ng-click="customizeWindow(textsource.source)\">Support</div> </p>
If you can't change server side, have a look at this example :
1) tell $sce your content is fine
$scope.message = $sce.trustAsHtml(json.key.text);
2) recompile your dynamicaly added content
$scope.init = function () {
var el = document.getElementById("dynamic");
$compile(el.childNodes[0])($scope);
};
NOTE: the recompile step is manual for now (press the recompile button). Follow this to make it work nicely.
I'm looking to programmatically add ng-* HTML attributes to various DOM elements. I've had some success with using $compile(obj)($scope); but this secondary compile causes issues with a number of components.
I add the ng-* attributes via jQuery... and yes, I know, directives, but this won't work for me as the ng-* HTML attributes I'm adding are boilerplate actions based on DOM structures. That and directives seem clunky (to say the least) as compared to jQuery DOM manip.
So... is there any way I can add in these boilerplate ng-* HTML attributes BEFORE Angular runs so that I can avoid the re-$compile? What I'd really love is a way to do a pre-init hook on Angular, is there such a beast?
SOLUTION:
#ChrisMartin sent me on the right path to figure out an answer to this question (thanks Chris!). What I ended up doing is this...
First I created a file named "angular-defer-bootstrap.js" that is included before "angular.js" with the following code:
//# Set the window.name to signal Angular to delay bootstrapping until `angular.resumeBootstrap()` is called.
//# See: http://stackoverflow.com/a/21049890/235704 and https://docs.angularjs.org/guide/bootstrap
//# NOTE: This MUST be included BEFORE angular*.js
window.name = 'NG_DEFER_BOOTSTRAP! ' + window.name;
I then created the following function with jQuery to preform any pre-Angular bootstrap code:
//####################
//# Setup the jQuery onDocumentLoad event to handle the pseudo-ng-directive of ng-preinit
//####################
$(document).ready(function () {
var $this, $pre = $('[ng-preinit]');
//# If we have some [ng-preinit]'s to process
if ($pre.length > 0) {
//# Traverse the [ng-preinit] attributes, eval'ing/running each and removing them so Angular doesn't freak out
$pre.each(function() {
$this = $(this);
eval($this.attr('ng-preinit'));
$this.removeAttr('ng-preinit');
});
}
//# Let Angular know it can .resumeBootstrap and remove the flag from window.name
angular.resumeBootstrap();
window.name = window.name.replace('NG_DEFER_BOOTSTRAP! ', '');
});
This is then utilized by including a ng-preinit pseudo-Angular directive/HTML attribute:
<div class="row" ng-controller="IndexController" ng-init="init()" ng-preinit="globalScope.preinit()">
The rub here is that the eval'd code contained within the pseudo-Angular directive ng-preinit has the global scope, rather than the Angular controller's $scope.
With these few lines of code, I can now cleanly hook the "pre-init" (that is, pre-bootstrap) of Angular and do whatever I like without the need to re-$compile (and it's unintended consequences), which is exactly what I wanted!
This is explained in Angular's documentation on manual initialization.
If you need to have more control over the initialization process, you can use a manual bootstrapping method instead. Examples of when you'd need to do this include using script loaders or the need to perform an operation before Angular compiles a page.
All, we're developing a webapp with AngularJS and we have a use case/requirement (that won't happen very often at all) where we will need to retrieve a complete HTML document from our static server. However, it appears that the $http object returns a raw HTML string as its 'data'. We are trying to avoid using an external library (like jQuery, for instance), but we need to parse that raw HTML string into a queriable DOM object. We could use an iframe and be done with it, but we're also trying to avoid using iframes for well-known reasons.
So, the question is: does AngularJS have a parser for HTML (as it does for JSON)? Or else, what's the most graceful way to handle this case?
P.S.: We tried sifting through Angular's API docs, but in all honesty they are hit-or-miss and unintuitive to navigate around.
If you need to get a DOM element from the string programmatically, parsing html into a DOM object is pretty simple.
Basically you'd use DOMParser.
var parser = new DOMParser();
var doc = parser.parseFromString('<div>some html</div>', 'text/html');
doc.firstChild; //this is what you're after.
From there if you wanted to query to get elements from it with vanilla JS (meaning, you don't want to use JQuery for some reason), you can do this:
//get all anchor tags with class "test" under a div.
var testAnchors = doc.firstChild.querySelectorAll('div a.test');
... but note: querySelectorAll is only supported in IE8 and higher.
EDIT: additional approach...
The "wrap" method:
var div = document.createElement('div');
div.innerHTML = '<div>some html</div>';
var result = div.childNodes;
... do note that this method will return HTMLUnknownElements if you put SVG or MathML into it. They'll "look" normal, but they won't work.
First of all, Angular uses jQuery as well. (jQuery lite)
From FAQ
Does Angular use the jQuery library?
Yes, Angular can use jQuery if it's present in your app when the
application is being bootstrapped. If jQuery is not present in your
script path, Angular falls back to its own implementation of the
subset of jQuery that we call jQLite.
However, I think you don't need full jQuery function here anyway.
That is what I did.
I use a directive and get the html as template and set replace as true.
jsFiddle
<myhtml></myhtml>
angular.module('myApp', []).directive('myhtml', function($http) {
return {
restrict: 'E',
scope: {},
template:'',
link: function(scope, element, attrs) {
$http.post('/echo/json/', data).success(function(re) {
element.html(re.html);
});
}
}
});
Edit note:
I just update the jsFiddle.
I include jquery on top for echoing the request in jsFiddle. In real, you don't need that.
However, it shows you that you can use jQuery in Angular.
If your html doesn't contain any angular tag, this example should work as your expectation .
Otherwise, you need to use compile instead of link.