Check form for changes in AngularJS - angularjs

I have an HTML page built using AngularJS. The page has a form containing a number of fields.
I have a Save, Back and Cancel button. When you click the back button I would like to be able to tell if changes have been made to the field and prompt the question "Would you like to save your changes?".
If you click the Cancel button, I want to ignore any changes made and go back to the previous page. How can this be achieved in Angular?

fYou can use "$locationChangeStart" https://docs.angularjs.org/api/ng/service/$location
$scope.$on('$locationChangeStart', function(event, newURL) {
if (newURL.lastIndexOf("#/") >= 0) {
$scope.locationToMove = newURL.substring(newURL.lastIndexOf("#/") + 1); // here you can store the location to move for future use
} else {
$scope.locationToMove = "/";
}
if ($scope.form.$dirty && !goToBack && !saved) {
$scope.displayConfirmationModel = true; // any alerts you want to show here
event.preventDefault();
}
else {
// you can move to that location
}
});
In the if you can check any change condition , its just for example I have given. You can do this for any location change , but if you want to do this on cancel or back button then you can have the same condition on the button click method and check for change .i.e if the form filed is dirty.

Related

Detect react event from Tampermonkey

I'm enhancing a React front end with Tampermonkey , by adding highlights to show cursor location in a grid, and allowing users to directly enter data , rather than then enter data.
After 2 or 3 cursor moves or data entry the grid refreshes or updates - no page change - and looses the highlighting I set up.
I'd like to catch the refresh/update and reset the highlighting.
I'm a noob..
The network tab shows post events so I tried https://jsbin.com/dixelocazo/edit?js,console
var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send;
to try and use POST events to detect the refresh. No joy !
I also looked at ajax events.
No luck :(
Can someone point me in the right direction here ?
Once I catch the event, I can then reset the highlighting to fix the problem
Since normally the userscripts run in a sandbox, JavaScript functions or objects cannot be used directly by default, here's what you can do:
Disable the sandbox:
// #grant none
You won't be able to use any GM functions, though.
Run in the page context via unsafeWindow:
const __send = unsafeWindow.XMLHttpRequest.prototype.send;
unsafeWindow.XMLHttpRequest.prototype.send = function () {
this.addEventListener('loadend', e => {
console.log('intercepted', e);
}, {once: true});
__send.apply(this, arguments);
};
Use MutationObserver to detect changes in page DOM:
const observer = new MutationObserver(mutations => {
const matched = [];
for (const {addedNodes} of mutations) {
for (const n of addedNodes) {
if (!n.tagName)
continue;
if (n.matches('.prey:not(.my-highlight)')) {
matched.push(n);
} else if (n.firstElementChild) {
matched.push(...n.querySelectorAll('.prey:not(.my-highlight)'));
}
}
}
// process the matched elements
for (const el of matched) {
el.classList.add('my-highlight');
}
});
observer.observe(document.querySelector('.surviving-ancestor') || document.body, {
subtree: true,
childList: true,
});
.surviving-ancestor means the element that isn't replaced/recreated by the page script. In devtools element inspector it's the one that isn't highlighted temporarily during DOM updates.
See also Performance of MutationObserver.

implementation of custom validation on click of Save & Submit Button in angularjs

I am new to angularjs and I need to develop single page application. I have a requirement of implementation of angular validation.
I have 10 fields(input, select and listbox) on page and 2 buttons(Save and Submit). When i click on save then 6 fields(just for example) should have valid values and when i click on Submit button- 8 fields should be checked.
But problem is. if i used form tag on page then how to implement these validation.
Your help will be appreciated.
write this code in a controller
obj.hasErrorWithsubmit = function (form, field, validation) {
if (validation) {
return ($scope.submitted && form[field].$error[validation]);
}
return (form[field].$dirty && form[field].$invalid) || ($scope.submitted && form[field].$invalid);
};
obj.hasErrorWithsave = function (form, field, validation) {
if (validation) {
return ($scope.save && form[field].$error[validation]);
}
return (form[field].$dirty && form[field].$invalid) || ($scope.submitted ``&& form[field].$invalid); };
Write this in html
ng-class="{'classname':obj.hasErrorWithsubmit(Formname,'fieldname','validationType')}">
i.e
ng-class="{'classname':obj.hasErrorWithsubmit(myform,'textfield1','required')}">
ng-class="{'classname':obj.hasErrorWithsave (myform,'textfield2','required')}">
classname is a css class which makes the border red
By clicking on submit button make $scope.submitted =true
By clicking on save button make $scope.save =true

UI grid check box selection change in a call back function

To check/uncheck the check box value, when the sweet alert cancel event is selected.
here in the call back function, not able to reset the check box value.
$scope.updateRow = function(row) {
SweetAlertService.confirm('Are you sure?','', function(isConfirmed) {
if (isConfirmed) {
}else{
if(row.entity.employed == "Y"){
row.entity.employed = "N";
}else if(row.entity.employed == "N"){
row.entity.employed = "Y";
}
});
Code here . http://plnkr.co/edit/Sd7Uk5yTkhPFnzrsDknp?p=preview
The changes needed to run this are as follows:
In SweetAlert.js set the timer to some bigger value. Current is 1500, set to timer: 150000.
Include onRegisterApi in grid definition and after resetting the value of checkbox on click of cancel just refresh the grid using $scope.gridApi.core.refresh()
Updated Plunker code: Here
Hope this helps!

Setting Attributes within Angular Directives: Radio Button > set > checked = true

EDIT PLUNKER EXAMPLE: http://plnkr.co/edit/WuiCAmMwbQnC0n197LSJ?p=preview
In the examples "sa" shoulbe checked and remain as checked. It is checked for a short time and then it looses its check status. I dont now why?
I am using a classical old fashion radio-button-based-navigation-tab-menu with Angular-UI-Router, it works well. Each click on a tab gets its URL.
If a user puts the URL manually into the adress bar of a browser and presses enter, the proper URL's content will be shown, it is also OK.
But my tab menu doesn't react on the manually changes at the adress bar. The correponding radio button should be checked. Therefore I've written a directive:
.directive ('checkIfMe', function (){
return {
link: function (scope, e, a) {
////////////////
if (currentUrl == currentNaviElement) {
console.log("Yes it is");
a.$set("checked", true);
}
}
}
I can detect the correct radio button, I see "yes it is" and I want to set its checked attribute to true. I've tried:
e.g. The ID of the current radio button is "navRadio_sa"
a.$set("checked", true);
a.checked = true;
$('#'+a.id+'').prop("checked",true);
All of them didn't work. But it I try it in the firebug console
$('#navRadio_sa').prop("checked",true);
it works. Where is my mistake?
Last but not least, that is a:
Try this
.directive('checkIfMe', function ($timeout) {
return {
link: function (scope, e, a) {
scope.my.info.e.push(e);
scope.my.info.a.push(a);
console
$timeout(function(){
if(a.id == "navRadio_sa") {
e.prop("checked", true);
var me = (a.id).replace("navRadio_","");
}
}, 10);
}
}
});
The e variable is a jQuery object of the element itself. You can work with it the same way that you'd normally work with jQuery objects.
I wrapped it in a timeout of 10 ms to give the ng-repeat time to complete before manipulating the dom. IT looks like ti was not working before because of a race condition. By setting the timeout, it should alleviate the issue.

How to set blank or null value of input field on back button press in angularjs

Could you please tell me how to set blank or null value for an <input> field so it is blank when I press the back button press in AngularJS?
I will explain my question:
When I run index.html file, it shows one form.
I fill name :"naveen" and password :"sharma" and click "Forget password".
It still show sign up page
When I click the back button ("present on top header or square one"), it shows the first page again - i.e. the login page with same (original) entry values name ="naveen" and password =`"sharma".
I need to reset these fields i.e. means it shows blank or null..
Here is my code:
function authenticationCntrl($scope,$state,Auth) {
$scope.user = [];
console.log('=====authenticationCntrl controller call')
console.log($scope.user.username)
console.log($scope.user.password)
$scope.forgetPassword = function () {
if($scope.user.username==Auth.username && $scope.user.password==Auth.password ){
$state.go('signup')
}
}
}
You can see it running here http://goo.gl/P5RsDU
to check out put please press preview button
Change for forgetPassword function as shown below:
$scope.forgetPassword = function () {
if($scope.user.username==Auth.username && $scope.user.password==Auth.password ){
$state.go('signup');
$scope.user.username = '';
$scope.user.password ='';
}
}

Resources