How to create href link inside controller in Angularjs? - html

I am showing a flash error message if a mobile number is not validated.
Flash message as "Mobile number not validated. click here to validate".
But I want to display the same error message with "click here" as the hyper link which will redirect me to the top of the page.
if (res.json.response.mobilevalidated == false) {
FlashService.Error("Mobile number not validated." + ( click here ) +" to validate", false);
$scope.disabled = function() {
$scope.model.disabled = true;
$scope.title = "Cannot access until mobile number is validated.";
}
} else {
$scope.model.disabled = false;
}
How can I use html tags inside the controller? As my error message is a dynamic one.

Use ng-include.
Js add
$scope.includePath = function () {
`templateUrl="..../your template path"`
};
HTML
<div ng-include="includePath" > New html is here </div>
Here in this case you can use <button> if you want to give click event.

HTML
<div ng-class="{ 'alert': flash, 'alert-success': flash.type === 'success', 'alert-danger': flash.type === 'error', 'selected': hlink}" ng-click = "linking()" ng-if="flash" ng-bind="flash.message" style="margin-top: 20px; ">
</div>
My Controller
if (res.json.response.mobilevalidated == false) {
$scope.linking = function(){
$location.path('/otp');
}
$scope.hlink =" click here";
FlashService.Error("Mobile number not validated." + $scope.hlink +" to validate" , false);
}

What you are looking for can be achieved using $sce that is included in Angular. Take a look at the Documentation here: https://docs.angularjs.org/api/ng/service/$sce
You basically define your HTML string as trusted in the Controller like this: $sce.trustAsHtml(Stackoverflow") and bind it in the template using ng-bind-html like <span ng-bind-html="mySuperCoolLink"></span>.
There is an example in the documentation liked above.
Edit:
Your function FlashService.Error receives an invalid string. You use string concatenation to include your HTML link, however, that only works if your HTML link is stored in a variable. So you have to do one of the following:
A)
FlashService.Error("Mobile number not validated. click here ) to validate", false);
or B)
var link = "( click here )";
FlashService.Error("Mobile number not validated." + link + " to validate", false);
In your provided code, the JS engine will recognise the round brackets as they are valid JS, but not the pointy brackets (I forgot their name...).
Edit 2:
Plunkr: https://plnkr.co/edit/WzzWtnJW98u3e7eTLn2q?p=preview

Related

Appending access code input into URL as utm tag

I'm currently building a landing page with an access code form field.
I'm stuck on finding a way to get the access code entered into a form to be appended as a tag on the url.
Enter "12345" into field and on submit direct to url "www.website.com/?code=12345"
Below is the code I have so far - :
<script>
function btntest_onclick(){
if (document.getElementById('input-code').value == '1234','5678','9809') {
var domain = "http://www.website.com?";
var data = $(this).serialize();
window.location.href = url
}
else {
alert ( 'not found' );
}
};
</script>
<center>
<span class="text-container">
<input type="text" name="accesscode" placeholder="ACCESS CODE" maxlength="10" size="25" id="input-code">
<p>ENTER</p>
</span>
</center>
Any advice on this would be greatly appreciated!
Thanks.
You have a few problems in the code:
The if containing document.getElementById('input-code').value == '1234','5678','9809'. That's not a valid conditional statement in JS. I assume you were trying to test if the value was equal to any of the strings, which can be done using || (A logical "or").
The code was never added to the end of the URL.
You never defined the url variable you were redirecting to.
Here's a commented version that should explain some ways to do this:
function btntest_onclick() {
// First, we assign the value to a variable, just to keep the code tidy
var value = document.getElementById('input-code').value
// Now we compare that variable against each valid option
// if any of these are true, we will progress
if (value === '1234' || value === '5678' || value === '9809') {
// Use a template literal (The ` quotes) to build the new URL
var url = `http://www.website.com?code=${value}`
// This could also be written as:
// var url = "http://www.website.com?code=" + value
// Navigate to your new URL (Replaced with an alert as a demonstration):
alert(url)
// window.location.href = url
} else {
// Otherwise, show the alert
alert('not found')
}
}
<center>
<span class="text-container">
<input type="text" name="accesscode" placeholder="ACCESS CODE" maxlength="10" size="25" id="input-code">
<p>ENTER</p>
</span>
</center>

Adding HTML content to angular material $mdDialog

I have written the following piece of code to display some contents in angular material dialog box. it works fine when i add plain text to textContent . when i add HTML its displays HTML as text. how do i bind HTML to textContent
This Works
Sample Link
$scope.Modal = function () {
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('body')))
.clickOutsideToClose(true)
.textContent('sample text')
.ok('Ok')
);
}
This Doesn't Works
Sample Link
$scope.Modal = function () {
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('body')))
.clickOutsideToClose(true)
.textContent('<div class="test"><p>Sample text</p></div>')
.ok('Ok')
);
}
Thanks in advance
You need to append to the template,
$mdDialog.show({
parent: angular.element(document.body),
clickOutsideToClose: true,
template: '<md-dialog md-theme="mytheme">' +
' <md-dialog-content>' +
'<div class="test"><p>Sample text</p></div>' +
' <md-button ng-click="closeDialog();">Close</md-button>' +
' </md-dialog-content>' +
'</md-dialog>',
locals: {
},
controller: DialogController
});
DEMO
You can add html in template and just add variable in displayOption. This will work.
Template Code
<script type="text/ng-template" id="confirm-dialog-answer.html">
<md-dialog aria-label="confirm-dialog">
<form>
<md-dialog-content>
<div>
<h2 class="md-title">{{displayOption.title}}</h2>
<p>{{displayOption.content}} <img src="{{displayOption.fruitimg}}"/></p>
<p>{{displayOption.comment}}</p>
</div>
</md-dialog-content>
<div class="md-actions" layout="row">
<a class="md-primary-color dialog-action-btn" ng-click="cancel()">
{{displayOption.cancel}}
</a>
<a class="md-primary-color dialog-action-btn" ng-click="ok()">
{{displayOption.ok}}
</a>
</div>
</form>
</md-dialog>
</script>
Controller Code
$mdDialog.show({
controller: 'DialogController',
templateUrl: 'confirm-dialog-answer.html',
locals: {
displayOption: {
title: "OOPS !!",
content: "You have given correct answer. You earned "+$scope.lastattemptEarnCount,
comment : "Note:- "+$scope.comment,
fruitimg : "img/fruit/"+$scope.fruitname+".png",
ok: "Ok"
}
}
}).then(function () {
alert('Ok clicked');
});
Use template instead of textContent, textContent is used for show plan text in a model. It does not render HTML code
$mdDialog.show({
controller: function ($scope) {
$scope.msg = msg ? msg : 'Loading...';
},
template: 'div class="test"><p>{{msg}}</p></div>',
parent: angular.element(document.body),
clickOutsideToClose: false,
fullscreen: false
});
You can use htmlContent instead of textContent to render HTML. Heres an excerpt from the documentation available at https://material.angularjs.org/latest/#mddialog-alert
$mdDialogPreset#htmlContent(string) - Sets the alert message as HTML.
Requires ngSanitize module to be loaded. HTML is not run through
Angular's compiler.
It seems a bit counter intuitive to use a template when you only need to inject one or two things in. To avoid using a template, you need to include 'ngSanitize' for it to work.
angular.module('myApp',['ngMaterial', 'ngSanitize'])
.controller('btnTest',function($mdDialog,$scope){
var someHTML = "<font>This is a test</font>";
$scope.showConfirm = function(ev) {
// Appending dialog to document.body to cover sidenav in docs app
var confirm = $mdDialog.confirm()
.title('Please confirm the following')
.htmlContent(someHTML)
.ariaLabel('Lucky day')
.targetEvent(ev)
.ok('Please do it!')
.cancel('Sounds like a scam');
//Switch between .htmlContent and .textContent. You will see htmlContent doesn't display dialogbox, textContent does.
$mdDialog.show(confirm).then(function() {
$scope.status = 'Saving Data';
},
function() {
$scope.status = 'You decided to keep your debt.';
});
};
})
Notice the injected HTML:
var someHTML = "<font>This is a test</font>";
I found this example here.
The latest version of Angular Material Design API has predefined function for add HTML content to the alert dialog:
an $mdDialogPreset with the chainable configuration methods:
$mdDialogPreset#title(string) - Sets the alert title.
$mdDialogPreset#textContent(string) - Sets the alert message.
$mdDialogPreset#htmlContent(string) - Sets the alert message as HTML. Requires ngSanitize module to be loaded. HTML is not run through Angular's compiler.
$mdDialogPreset#ok(string) - Sets the alert "Okay" button text.
$mdDialogPreset#theme(string) - Sets the theme of the alert dialog.
$mdDialogPreset#targetEvent(DOMClickEvent=) - A click's event object. When passed in as an option, the location of the click will be used as the starting point for the opening animation of the the dialog.
The link to the documentation: Angular MD API

How can I create a list of buttons using AngularJS?

I have some data which is presented similar to a search system (list of links on different source):
First unit of data Show Detail
Second unit of data Show Detail
...
Each unit of data has id (orderedNumber) and some information which must be hidden by default. Each unit of data has button which shows this information. The button calls a function ShowHide. I have problem because this function doesn't work with several buttons. Information about the unit of data must be shown when I click on the button (data is determined dynamically).
html:
<div ng-repeat="x in results">
{{ x.orderNumber + '. ' + x.namePackage + ' ' + x.size + ' Bytes '}} <a href={{x.link}}>Download</a>
<input type="button" value="Show detail" ng-click="ShowHide(x.orderNumber)" />
<div ng-show = "IsVisible[orderedNumber]">response</div>
</div>
script.js:
$scope.ShowHide = function (orderedNumber) {
//This will hide the DIV by default.
$scope.IsVisible[orderedNumber] = false;
$scope.ShowHide = function (orderedNumber) {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible[orderedNumber] = $scope.IsVisible[orderedNumber] ? false : true;
}
};
How can I create a list of buttons using AngularJS?
Just use a property in the var instead of managing an array like this :
ng-click="ShowHide(x)"
ng-show = "x.visible"
$scope.ShowHide = function (item) {
item.visible = !item.visible
};
EDIT : If you don't have any more logic in the Showhide function you also could do this :
ng-click="x.visible = !x.visible"

Custom Google Search In Webpage [duplicate]

This question already has answers here:
How can I add an integrated Google search to my website?
(6 answers)
Closed 9 years ago.
I was wondering how i can make my own custom google search.
Can i do something like this :
<form action="http://www.google.com/search=q?+text input" method="get">
<input type="search">
<input type="submit">
</form>
Try custom search api provided by Google for this. Though it is not pure HTML.
The following code demonstrates how to render a search box, together with search results, in a div, using the explicit parsetag and function callback:
<div id="test"></div>
<script>
var myCallback = function() {
if (document.readyState == 'complete') {
// Document is ready when CSE element is initialized.
// Render an element with both search box and search results in div with id 'test'.
google.search.cse.element.render(
{
div: "test",
tag: 'search'
});
} else {
// Document is not ready yet, when CSE element is initialized.
google.setOnLoadCallback(function() {
// Render an element with both search box and search results in div with id 'test'.
google.search.cse.element.render(
{
div: "test",
tag: 'search'
});
}, true);
}
};
// Insert it before the CSE code snippet so that cse.js can take the script
// parameters, like parsetags, callbacks.
window.__gcse = {
parsetags: 'explicit',
callback: myCallback
};
(function() {
var cx = '123:456'; // Insert your own Custom Search engine ID here
var gcse = document.createElement('script'); gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>
This is the tutorial link.
Please refer the following steps to create google custom search
1.First u have Sign up to Google Account
2.go to this url https://www.google.com/cse/create/new
3.Then specify the website URL (where to search )
4.click on Create button
5.in the next page there are 3 buttons available from that Click on "Get Code" Button.
6.after clicking on that, its generate the code. Copy that code and paste in your webpage.
Google have their own walkthrough,
https://www.google.com/cse/

Using PUT method in HTML form

Can I use a PUT method in an HTML form to send data from the form to a server?
According to the HTML standard, you can not. The only valid values for the method attribute are get and post, corresponding to the GET and POST HTTP methods. <form method="put"> is invalid HTML and will be treated like <form>, i.e. send a GET request.
Instead, many frameworks simply use a POST parameter to tunnel the HTTP method:
<form method="post" ...>
<input type="hidden" name="_method" value="put" />
...
Of course, this requires server-side unwrapping.
XHTML 1.x forms only support GET and POST. GET and POST are the only allowed values for
the "method" attribute.
Can I use "Put" method in html form to send data from HTML Form to server?
Yes you can, but keep in mind that it will not result in a PUT but a GET request. If you use an invalid value for the method attribute of the <form> tag, the browser will use the default value get.
HTML forms (up to HTML version 4 (, 5 Draft) and XHTML 1) only support GET and POST as HTTP request methods. A workaround for this is to tunnel other methods through POST by using a hidden form field which is read by the server and the request dispatched accordingly. XHTML 2.0 once planned to support GET, POST, PUT and DELETE for forms, but it's going into XHTML5 of HTML5, which does not plan to support PUT. [update to]
You can alternatively offer a form, but instead of submitting it, create and fire a XMLHttpRequest using the PUT method with JavaScript.
_method hidden field workaround
The following simple technique is used by a few web frameworks:
add a hidden _method parameter to any form that is not GET or POST:
<input type="hidden" name="_method" value="PUT">
This can be done automatically in frameworks through the HTML creation helper method.
fix the actual form method to POST (<form method="post")
processes _method on the server and do exactly as if that method had been sent instead of the actual POST
You can achieve this in:
Rails: form_tag
Laravel: #method("PATCH")
Rationale / history of why it is not possible in pure HTML: https://softwareengineering.stackexchange.com/questions/114156/why-there-are-no-put-and-delete-methods-in-html-forms
for people using laravel
<form method="post" ...>
#csrf
#method('put')
...
</form>
Unfortunately, modern browsers do not provide native support for HTTP PUT requests. To work around this limitation, ensure your HTML form’s method attribute is “post”, then add a method override parameter to your HTML form like this:
<input type="hidden" name="_METHOD" value="PUT"/>
To test your requests you can use "Postman" a google chrome extension
To set methods PUT and DELETE I perform as following:
<form
method="PUT"
action="domain/route/param?query=value"
>
<input type="hidden" name="delete_id" value="1" />
<input type="hidden" name="put_id" value="1" />
<input type="text" name="put_name" value="content_or_not" />
<div>
<button name="update_data">Save changes</button>
<button name="remove_data">Remove</button>
</div>
</form>
<hr>
<form
method="DELETE"
action="domain/route/param?query=value"
>
<input type="hidden" name="delete_id" value="1" />
<input type="text" name="delete_name" value="content_or_not" />
<button name="delete_data">Remove item</button>
</form>
Then JS acts to perform the desired methods:
<script>
var putMethod = ( event ) => {
// Prevent redirection of Form Click
event.preventDefault();
var target = event.target;
while ( target.tagName != "FORM" ) {
target = target.parentElement;
} // While the target is not te FORM tag, it looks for the parent element
// The action attribute provides the request URL
var url = target.getAttribute( "action" );
// Collect Form Data by prefix "put_" on name attribute
var bodyForm = target.querySelectorAll( "[name^=put_]");
var body = {};
bodyForm.forEach( element => {
// I used split to separate prefix from worth name attribute
var nameArray = element.getAttribute( "name" ).split( "_" );
var name = nameArray[ nameArray.length - 1 ];
if ( element.tagName != "TEXTAREA" ) {
var value = element.getAttribute( "value" );
} else {
// if element is textarea, value attribute may return null or undefined
var value = element.innerHTML;
}
// all elements with name="put_*" has value registered in body object
body[ name ] = value;
} );
var xhr = new XMLHttpRequest();
xhr.open( "PUT", url );
xhr.setRequestHeader( "Content-Type", "application/json" );
xhr.onload = () => {
if ( xhr.status === 200 ) {
// reload() uses cache, reload( true ) force no-cache. I reload the page to make "redirects normal effect" of HTML form when submit. You can manipulate DOM instead.
location.reload( true );
} else {
console.log( xhr.status, xhr.responseText );
}
}
xhr.send( body );
}
var deleteMethod = ( event ) => {
event.preventDefault();
var confirm = window.confirm( "Certeza em deletar este conteúdo?" );
if ( confirm ) {
var target = event.target;
while ( target.tagName != "FORM" ) {
target = target.parentElement;
}
var url = target.getAttribute( "action" );
var xhr = new XMLHttpRequest();
xhr.open( "DELETE", url );
xhr.setRequestHeader( "Content-Type", "application/json" );
xhr.onload = () => {
if ( xhr.status === 200 ) {
location.reload( true );
console.log( xhr.responseText );
} else {
console.log( xhr.status, xhr.responseText );
}
}
xhr.send();
}
}
</script>
With these functions defined, I add a event listener to the buttons which make the form method request:
<script>
document.querySelectorAll( "[name=update_data], [name=delete_data]" ).forEach( element => {
var button = element;
var form = element;
while ( form.tagName != "FORM" ) {
form = form.parentElement;
}
var method = form.getAttribute( "method" );
if ( method == "PUT" ) {
button.addEventListener( "click", putMethod );
}
if ( method == "DELETE" ) {
button.addEventListener( "click", deleteMethod );
}
} );
</script>
And for the remove button on the PUT form:
<script>
document.querySelectorAll( "[name=remove_data]" ).forEach( element => {
var button = element;
button.addEventListener( "click", deleteMethod );
</script>
_ - - - - - - - - - - -
This article https://blog.garstasio.com/you-dont-need-jquery/ajax/ helps me a lot!
Beyond this, you can set postMethod function and getMethod to handle POST and GET submit methods as you like instead browser default behavior. You can do whatever you want instead use location.reload(), like show message of successful changes or successful deletion.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
JSFiddle: https://jsfiddle.net/enriquerene/d6jvw52t/53/
If you are using nodejs, you can install the package method-override that lets you do this using a middleware.
Link to documentation: http://expressjs.com/en/resources/middleware/method-override.html
After installing this, all I had to do was the following:
var methodOverride = require('method-override')
app.use(methodOverride('_method'))
I wrote an npm package called 'html-form-enhancer'. By dropping it into your HTML source, it takes over submission of forms with methods aside from GET and POST, and also adds application/json serialization.
<script type=module" src="html-form-enhancer.js"></script>
<form method="PUT">
...
</form>
In simple words - No.
I have tried to fire a put request in the HTML form, but it sends the POST request to the server. To add the PUT request -
We can do it by listening to the submit action in the script, then fire the put request to a particular endpoint.
Screenshot from the http-server env. test