How to properly escape special characters using ngSanitize? - html

I want to let user enter special characters such as "&" and then convert those to correct html when page is submitted. ex "&" => "&amp" I have read the examples and found ng-bind-html and $sce.
It seems ng-bind-html is useless for my need as it will only show html text sent from controller properly converted in the view. ex: it will show "&amp" as "&" to the user. So what I'm doing is converting the characters using "$sce" at the controller before sending it to server. Ex:
var accountName = $sce($scope.accountName);
Is this the correct way to do this? Or is there a straight forward way to bind the view to pass sanitized text to the controller, just like ng-bind-html but in a two-way binding? I'm using Angular 1.2.4.

Based on references and examples found under ngSanitize module included in angular-sanitize.js, the ideal way to parse input into properly escaped html string, is by using $sanitize component. Ex:
var accountName = $sanitize( $scope.accountName );
For this, it is required to include ngSanitize in the angular app module:
var myapp = angular.module('myapp',['ngSanitize']);
and included $sanitize in the controller where $sanitize is used:
myapp.controller('myctrl', [ "$scope", "$sanitize", function ( $scope, $sanitize) {
// code goes here
var accountName = $sanitize( $scope.accountName );
// further processing after sanitizing html input goes here
}
}]);
$sce is a service in angular that provides Strict Contextual Escaping, in which angular requires binding in certain contexts with values that are safe to be used. Further information can be found in angular documentation.

Related

Render HTML string in Node?

Alright, so I have downloaded Express, set the port with process.env.PORT || 8080, and set the app variable var app = express(). Now, what I'm trying to accomplish is instead of rendering HTML through a file, could I do it through a string?
var html = "<!DOCTYPE html>\n<html>\n <head>\n </head>\n <body>\n <h1>Hello World!</h1>\n </body>\n</html>";
app.get('/',function(req,res){
res.render(html);
});
Is there a possible way to do this?
the res.render method as specified in the doc : Renders a view and sends the rendered HTML string to the client. So you need to use a template engine eg : jade,ejs, handlebars.. but if your purpose is to only output some html you can do it with res.send instead.
Use res.setHeader set HTTP Response Header
res.setHeader("Content-Type", "text/html")
res.send(`
<h1>Mock API</h1>
`)
You could do it with a string but then you should convert the call to a Javascript call so only the part that needs to be replaced is displayed on the web page. The Ajax call gets from the Controller a : res.send("This is a String) back to its client. At the client you could put this result in a elements innerHtml and then you will have some kind of SPA :-)

Angularjs ng-grid using Grails JSON data

Angular ng-grid data binding question
I have a Groovy/Grails application that has a domain “Grid” class for which I have registered a custom “marshaller” to produce the JSON that I can use for an Angularjs ng-grid..
Say “grid” is and instance of the Grid class,
“grid as JSON” produces the desired JSON.
I have a Grails/groovy controller that loads the data and returns the JSON:
def index() {
def grid = Grid.first()
grid as JSON
}
But I don’t know how to get this JSON data into the ng-grid in my GSP:
<body ng-controller="MyCtrl">
<script>
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope) {
$scope.gridOptions = ${grid}; // NEED HELP HERE !
});
</script>
<div class="gridStyle" ng-grid="gridOptions"></div>
</body>
I don't know how to get the data into $scope.gridOptions. When I look at what is being generated with firebug, I see $scope.gridOptions is
{"columnDefs":[{"field": ...
which is the encoded JSON data. (The quotation marks are encoded). What is the best way to pass JSON data between a Grails back end and ng-grid in a JSP?
Thank you for the suggestion Sridhar, I started looking for ways to un-escape JSON within GSP, and I found the answer here:
how-to-render-json-properly-without-escaping-quotes-inside-a-gsp-script-tag
I need to use the g:applyCodec tag in my GSP:
<g:applyCodec encodeAs="none">
$scope.gridOptions = ${grid};
</g:applyCodec>

AngularJS: Dynamically load HTML tag retrieved from database

I am fetching the data from a JSON file using factory:
appService.factory('svr', ['$resource', function($resource) {
return $resource('data/:pageName.json', {}, {query:{method:'GET', isArray:true}});
}]);
and accessing it in controller:
appController.controller('requirementCtrl', ['$scope', 'svr', function($scope, svr){
$scope.ques = svr.query({pageName:'question'});
}]);
Data in the JSON file contains the label, four options and a type checkbox like value. I have to format it into an HTML tag using this data.
I find one way is to create an HTML tag in controller and bind it to div using ng-bind-html. Directives does not work as I have implemented ngRoute.
What's the best way to do it?
I think the solution is to "compile" your element like :
$compile(element.contents())(scope);
http://onehungrymind.com/angularjs-dynamic-templates/
Other solution maybe (By Ben Nadel): http://www.bennadel.com/blog/2449-directive-link-observe-and-watch-functions-execute-inside-an-angularjs-context.htm

How to get custom User data in Stormpath with expressJS?

Hi I want to get a custom JSON file from the stormpath API in a normal JS function instead of within a view.
The view method is like this:
var stormpath = require('express-stormpath');
app.get('/email', stormpath.loginRequired, function(req, res) {
res.send('Your email address is:', res.locals.user);
});
However when I attempt to just use the method like this:
var customD = res.send('Your email address is:', res.locals.user);
it returns an unexpected token ' ( ' error
In the posted example the quotation marks ’ are a rich encoded, not the standard single ' or double quotes ". I would replace your quotes with single quotes. What text editor are you using to write your node application?
Regarding the original question about custom data, can you show us how you are assigning the custom data properties? I suspect that you might have run into this issue: https://github.com/stormpath/stormpath-sdk-node/issues/88
Can you try the following code sample?
var stormpath = require('express-stormpath');
app.get('/email', stormpath.loginRequired, function(req, res) {
res.send('Your email address is:' + res.locals.user.email);
});
I suspect a few things:
Your code is running OUTSIDE of a route.
You have a comma in res.send(), so the send method thinks you're passing in additional arguments as opposed to a single string.
You're not using the email address directly.

Zend Jquery Autocomplete populate from Database

Hi I am trying to implement a autocomplete field using Zend Jquery. I followed a tutorial to grab the data from an array and I have extended the code to access the data from my mysql table.
IndexController.php
$this->view->autocompleteElement = new ZendX_JQuery_Form_Element_AutoComplete('ac');
$this->view->autocompleteElement->setLabel('Autocomplete');
$this->view->autocompleteElement->setJQueryParam('source', '/index/city');
This calls the cityAction()
public function cityAction()
{
$results = Application_Model_City::search($this->_getParam('term'));
$this->_helper->json(array_values($results));
}
I then call the Model City
public static function search($term)
{
$region = new Application_Model_DbTable_Regions();
$results = $region->getRegion($term);
return $results;
}
And finally the Regions db model
public function getRegion($term)
{
$select = $this->select()->from($this,'City')
->where('City LIKE ? ',$term.'%');
return $this->fetchAll($select)->toArray();
}
Now when I go the autocomplete field it shows the results but as UNDEFINED , I think its something to do the way I am send the data back to the json helper.
I used firebug and I can see the data is been pulled in the following format.
[{"City":"London"},{"City":"Londonderry"},{"City":"Longfield"},{"City":"Longhope"},{"City":"Longniddry"}]
I think this format is incorrect, please any body dealt with this before?
Cheers
J
The ZendX_JQuery_Form_Element_AutoComplete element is a proxy to the AutoComplete View Helper, which is a proxy to the jQuery UI Autocomplete widget.
If you read the overview on the jQuery UI Autocomplete page, you will note:
The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.
When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.
So, the JSON you are returning to the autocomplete should be structured more like:
[{"label":"London","value":"London"},{"label":"Londonderry","value":"Londonderry"},{"label":"Longfield","value":"Longfield"}]
Good luck!
Fixed the problem afters hours of pain!
I modified the below code where it accesses the data
public function getRegion($term)
{
$select = $this->select()->from($this,'City')
->where('City LIKE ? ',$term.'%');
return $this->fetchAll($select)->toArray();
}
I added a line of SQL City AS Value
public function getRegion($term)
{
$select = $this->select()->from($this,'City AS value')
->where('City LIKE ? ',$term.'%');
return $this->fetchAll($select)->toArray();
}
This seems to have worked!
Cheers
J