update angular form from javascript - javascript

I'm new to Angular. I've got an Angular js form that has rendered and works properly (updates, etc). I have a scenario where I want to populate form values based on user action after the form has rendered. So if the user takes a certain action, the values in a dropdown box, checkbox, input, etc, are preset in a certain way. I can get everything working except the last step.
From javascript, how do I update the data displayed on the form?
I've gone so far as to use
document.getElementById('123').value = 'my new default'
and although that works for plain text input fields, it doesn't change things like select dropdown boxes. They accept the new value, but still display a blank value. Is there any easy way to do this through the Angular framework?

You can update the value on an html form using angularjs like so:
angular.module('HelloWorldApp', [])
.controller('HelloWorldController', function($scope) {
$scope.greeting = "Hello World";
$scope.UpdateForm = function(){
$scope.greeting= "Updated!";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<div ng-app="HelloWorldApp">
<div ng-controller="HelloWorldController">
<input ng-model="greeting" />
<button ng-click="UpdateForm()">Update Form</button>
</div>
</div>
</html>
To get started with angular, I really enjoyed watching this video
Angular in 50 examples part 1

Related

make javascript variable update live with text input

hey this is an edited version of my first post:
Pretty much what I want to do is have a text input box that stores its contents in a javascript variable. The catch is I want it to happen live, so the variable will update automatically say, ever .2 seconds without the user needing to press a submit button. Thanks
Are you looking for the two way data binding? Something like this: https://codepen.io/manishiitg/embed/ZYOmbB?
<html>
<head>
<script src="https://code.angularjs.org/1.3.8/angular.min.js"></script>
<script>
var mainMod = angular.module('MainApp', []);
mainMod.controller('MainCtrl', function ($scope) {
$scope.text = '';
});
</script>
</head>
<body ng-app='MainApp'>
<div ng-controller='MainCtrl'>
<div>
Change Text Here:
<input type='text' ng-model='text' />
</div>
<div>
<p>Text: {{text}}</p>
</div>
</div>
</body>
<html>
You can achieve that with Angular, React and Vue.js framework, even with jQuery. Perhaps you should try one of the frameworks that solves your needs quickly.
If you choose Angular, I recommend you to make the tutorial steps, specially this part: https://angular.io/tutorial/toh-pt1#two-way-binding

Dynamically add angular attributes to old html forms

I have a project where I'm currently trying to refactor an old system that was hinged on jquery from the ground up with angular 1.x. However, there are a lot of old HTML forms that I'd like to reuse the bulk of so I don't want to recreate them. I'd love it if there was a way to keep it purely angular, but I'm honestly at a loss of how I'd do that (or whether or not I can). I'm fairly new to angular so there are a lot of inner workings to it that I'm still not privy to.
I've searched around on google and other places including here and I can't really even find other people talking about it. That tells me that either I'm searching badly or it's something that I should probably not be working towards.
All the html pages have identically id'd fields so I feel I can reliably base things on that. For example: all forms with first name text boxes have an id of "cl_fname".
Is there anyway that I can accomplish: getting the form, adding an ng-model="cl_fname" or something to the relevant tag and then display the form? I've gotten to the point where I can get the html page, hold it in the scope and then display using ng-bind-html, but figuring out how to add angular attributes to specific elements I can't figure out.
You can achieve this with jQuery and the attr() method.
I created a plunker here that demonstrates adding angular to an existing "plain" html form.
In the example, I'm using id selectors, but you could use any combination of selectors to ensure you get the right elements.
The below is a quick code snippet from my Plunker example:
HTML:
<div ng-app="myApp">
<form id='myForm1' data-test="test2">
<span>First Name:</span>
<input type="text" id="myForm1_firstName" />
<input type="submit" id="myForm1_Submit" value="Go!" />
</form>
</div>
JS:
// set up angular
var myApp = angular.module('myApp', []);
myApp.controller('MyForm1Controller', ['$scope', function($scope) {
$scope.firstName = 'Angular Working!';
}]);
// use jQuery to add the relevent attributes to our form
var jqMyForm1 = $('form#myForm1');
var jqTxtFirstName = jqMyForm1.find('input[type="text"]#myForm1_firstName');
//add controller to form
jqMyForm1.attr('ng-controller', 'MyForm1Controller');
//bind the textbox to the angular 'firstName' variable
jqTxtFirstName.attr('ng-model', "firstName");
EDIT:
just realised you want to load the html form dynamically.
Version 2 of the plunker (here) will now dynamically load a HTML form from an external resource (separate html page), inject it into the current page, add the angular bindings to it, and then get angular to recognise it.
The key to getting angular to recognise the form is the use of the $compile object (angular $compile documentation).
Again, quick snippets of the code in use:
HTML (main page):
<div ng-app="myApp" ng-controller="LoadingController"></div>
HTML (myForm1.html):
<form id='myForm1' data-test="test2">
<span>First Name:</span>
<input type="text" id="myForm1_firstName" />
<input type="submit" id="myForm1_Submit" value="Go!" />
</form>
JS:
// set up angular
var myApp = angular.module('myApp', []);
// main controller for loading the dynamic form
myApp.controller('LoadingController', ['$scope','$http','$compile', function($scope,$http,$compile) {
$scope.loadHtmlForm = function(formURL) {
$http.get(formURL).then(function successCallback(response){
var jqForm = $(response.data);
var jqTxtFirstName = jqForm.find('input[type="text"]#myForm1_firstName');
//add controller to form
jqForm.attr('ng-controller', 'MyForm1Controller');
//bind the textbox to the angular 'firstName' variable
jqTxtFirstName.attr('ng-model', "firstName");
$('div').append(jqForm);
$compile(jqForm[0])($scope);
});
}
$scope.loadHtmlForm('myForm1.html');
}]);
// form controller for managing the data
myApp.controller('MyForm1Controller', ['$scope', function($scope) {
$scope.firstName = 'Angular Working!';
}]);

Angularjs, checking if radio buttons in form have been selected

I'm starting with AngularJS, and I'm building a multi-step form where user has to fill different pages. When finished a page, he's allowed to press a next button and fill the following page.
For the first page, I've built in the HMTL a form (named pageOneForm), with different text input fields, marked as required, and in the relative controller I'm doing this watch:
$scope.$watch('pageOneForm.$valid', function(validity) {
ModelData.actualPageCompleted = validity;
})
And it works like a charme. My model (ModelData) is updated.
I was trying to apply the same logic to the following part of the app, the second page. Instead of input text, the user has to select two options from 2 different radio buttons groups.
So I built in the html a list of buttons via ng-repeat :
<div ng-Controller="PageTwo" ng-show='data.actualPage == 2'>
<form name="pageTwoForm">
<h3>General Information > Knowledge About </h3>
<div>
<b>User</b>
<div ng-repeat="option in userOptions">
<input type="radio" name="userGroups" ng-model="data.knowledgeAboutUser" ng-value="option.id" id="{{option.id}}" required>{{option.text}}
</div>
<div ng-repeat="option in targetGroupUserOptions">
<input type="radio" name = "targetUserGroup" ng-model="data.knowledgeAboutTargetGroup" ng-value="option.id" id="{{option.id}}" required>{{option.text}}
</div>
</div>
</form>
and I've implemented the same code as above in its controller:
$scope.$watch('pageTwoForm.$valid', function(validity) {
ModelData.actualPageCompleted = validity;
})
but apparently it doesn't work, and in my model actualPageCompleted is always true...
What am I doing wrong?
Thanks
I did my best to create a controller with some dummy data to get a fiddle working with your example code. Here is the fiddle You need to force the $digest cycle to update your form's validity state on ng-click for the radio buttons (see this SO post for more details), which is why the method
$scope.forceDigest = function(){
setTimeout(function(){ $rootScope.$$phase || $rootScope.$apply(); });
};
is necessary. Alternatively, you can get rid of the method call and uncomment the html code
<h3 ng-show="false">{{data.knowledgeAboutTargetGroup}}</h3>
<h3 ng-show="false">{{data.knowledgeAboutUser}}</h3>
in the fiddle to force the form object to update as well.
And I would make sure that ModelData.actualPageCompleted is not retaining its true value from when pageOneForm.$valid became true and it was set.
I hope that this helps!

Change text input value with jQuery - Chrome extension

I am trying to change input value in particular web site from chrome extension. In order to do that I am using jQuery in my content script. It works in most of the cases, but I didn't manage to change value of the input when it is part of AngularJS view. I found the same problem when I use let say kendoUI. I am trying to set the value calling $('element').val('value') and then try to call blur and change event, but without any success.
I went through may be 99% of the posts related to this topic, but still can't find working solution.
You just need to Call $scope.apply() in order to let angular know about updating the bindings. This is mainly because by default, angular doesn't know anything about the changes you are making in jQuery.
Below is a sample code, and here is a jsFiddle. Hope this helps.
app.controller('testCtrl', ['$scope', function ($scope) {
$scope.changeValue = function() {
$('#test').val("new Value");
$scope.apply();
}
<div class="form-inline">
<input type="text" id="test" value="test">
<input type="submit" value="submit" ng-click="changeValue()">
</div>

Populate form field with javascript

I have a form with several fields populated by the user and before it is submitted some javascript gets called when a check button. It tries to set the value of the form fields to a variable that exists in the js function.
document.getElementById('var1').innerHTML = test;
alert(test);
I know the javascript is working as expected because I see the alert but the form boxes are not getting populated:
#helper.input(testForm("var1")) { (id,name,value,args) => <input type="text" name="#name" id="#id" #toHtmlArgs(args)> }
innerHTML is used to get/set the body of an html tag, so you're probably ending up with this in the html:
<input ...>test</input>
I think this may work for a <textarea>, but for your <input type="text"> you want to set the value attribute.
document.getElementById('var1').value = test;
If you want to programmatically set an html form field via JS there are many ways to do this and many libraries out there that make it really easy.
Such as various JS two-way component template binding libraries.
For instance, you can simply do the following:
HTML:
<div id="myapp">
<input id="var1"/>
<button>Submit</button>
</div>
JS:
mag.module('myapp',{
view : function(state){
var test= 'tester';
state.button= {
_onclick:function(){
state.var1=test
}
}
}
});
Here is working example of the above example:
http://jsbin.com/ciregogaso/edit?html,js,output
Hope that helps!

Categories

Resources