<form class="well form-search">
<input type="text" id="reference" ng-model="reference" name="reference" class="input-large search-query">
<button ng-click="getDetail(reference)" class="btn">Search</button>
</form>
I have a function that updates the reference input and gives it focus, however the ng-click function on the button fails to fire
New to angular
function reffocus(ovalue) {
$("#reference").val(ovalue);
$("#reference").focus();
}
Something like this will work (and here is a plunker):
*Note: if you already have ng-app and ng-controller setup you don't need to set them here.
<form class="well form-search" ng-app="myApp" ng-controller="Ctrl">
<input type="text" id="reference" ng-model="reference" name="reference" class="input-large search-query">
<button ng-click="getDetail()" class="btn">Search</button>
</form>
Javascript:
var myApp = angular.module('myApp', []);
myApp.controller('Ctrl', function($scope) {
$scope.getDetail = function() {
// $scope.reference will be initialized by ng-model
console.log($scope.reference);
}
});
Notice how Davin did not use jQuery in his solution. If you are new to angular, you need to temporarily drop jQuery. It is a crutch and will really slow down your learning process. You might get a little frustrated but hang in there. You can do a lot of jQuery stuff with angular. I know it really helped me in the beginning. Now I use jQuery only when it is appropriate.
Related
I have this as HTML:
<div class="row" ng-app="">
<form>
<input type="text" ng-model="link" name="link"
class="form-control" id="yesklinkshjhs3"
value="hello" placeholder='Link for your post.'>
</form>
<small></small>
</div>
I have created this HTML just to show the problem so there may be some mistakes but the main issue is that the textbox cant is prefilled with any value if I use the ng-model there.
If I remove the ng-model the value is there. I need the form to be prefilled to facility the editing of a post, how should I do that ??
I have tried removing the ng-model it works then but I need the ng-model there to show the realtime change in the next box.
I am new to the angular.
Here is a fiddle
http://jsfiddle.net/iamrahulkumar001/wksapfr2/
The textbox does not have any prefilled value ...
There's a few things with your JSFiddle that need to be fixed. First, you'll need to use the ng-app directive to bootstrap your application. Second, you should be registering MyCtrl as a controller. Third, you can set a default value for inputValue in your MyCtrl controller. Below is a working example demonstrating these three items.
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
$scope.inputValue = 'sjks';
$scope.$watch('inputValue', function(thisValue) {
$scope.inputValueEcho = thisValue;
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<input data-ng-model="inputValue" data-ng-trim="false" value='sjks'/>
<p>This value: ----<span data-ng-bind="inputValue"></span>----</p>
<p>This value (echo): ----<span data-ng-bind="inputValueEcho">dddddd</span>----</p>
</div>
I have a code like this:
<div class="form-group">
<div class="col-sm-8 col-md-offset-4">
<label class="ui-radio"><input name="radio1" type="radio" value="A" ng-model="$data.choice" ng-change="onChoice()"><span>A</span></label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-md-offset-4">
<label class="ui-radio"><input name="radio1" type="radio" value="B" ng-model="$data.choice" ng-change="onChoice()"><span>B</span></label>
</div>
</div>
As you can see, there's a $data.choice ng-model that should trigger a "onChoice()" function when changed, defined at the controller (the ng-controller is defined at the view and works properly). The problem is that the function doesn't trigger, but if I erase the "$data" and leave it like ng-model="choice" it works perfectly.
$data is just a variable defined by me at the $scope. I can actually trigger the onChoice() with a button and ng-click, but it doesn't work with the ng-change. I guess it's a problem with ng-change but I don't know what's happening.
Edit
Ok as I see that it's not that simple, I'll add some information:
Here's my controller, It includes some interaction with the $parent controller so I don't know if that could affect:
$scope.data = $scope.$parent.data;
$scope.data.choice = $scope.data.choice || 'vote';
$scope.onChoice = function(){
//stuff
};
I know that logic when initilizing the variable seems strange but that's important, I just simplified the code. Maybe I could change my logic in order to use just $scope.choice instead of $scope.data.choice, but I still want to know why isn't this working.
Even though the "ng-model" is there, the "onChoice" function is working fine.
Once check your controller logic.
I wrote a sample program. and check out in the Plunkr
angular.module('todoApp', [])
.controller('TodoController', ['$scope', function($scope) {
$scope.onChoice = function(){
alert("changed.");
};
}]);
I am trying to use the value of $scope.commentText but when I call addComment() the scoped variable is empty eventhough it is bound. As a workaround I pass the commentext as a parameter value that works but still it should work. My question how do I clear out commentText which is bound to a text input ... but it does not work as expected either. I looked around... and I am missing something cause I am doing exactly as the docs tell me how to. So... anyone?
$scope.user = "WM";
$scope.commentText='';
$scope.addComment = function(plan, commentText) {
console.log(commentText)
plan.comments.push({text:commentText, user:$scope.user);
commentText=null;
$scope.commentText=null;
};
and the view:
<form ng-submit="addComment(plan, commentText)">
<div class="input-group">
<input class="form-control" type="text" ng-model="commentText" size="30" placeholder="add new comment here">
<span class="input-group-btn">
<input class="btn btn-primary" type="submit" value="add">
</span>
</div>
</form>
plunker: http://plnkr.co/edit/lG0Ckjctsj9Hu83lTydh?p=preview
use this.commentText=null; instead of $scope.commentText=null in the addComment method.
Updated your plunkr
Edit: I started typing up an explanation when I noticed there is an excelent one right here:
'this' vs $scope in AngularJS controllers
I am going through learning curve with AngularJs and I am finding that there are virtually no examples that serve real world use.
I am trying to get a clear understanding of how to submit a form with the most standard components and pass it on to a PHP file..
My fiddle.
Does anyone have any good examples on submitting simple, un-polluted, forms that would help me and probably numerous other Angularjs beginners..
When I say a clean form I am referring to something like this..
<div ng-app="myApp">
<form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">
First name: <br/><input type="text" ng-model="form.firstname"> <br/><br/>
Email Address: <br/><input type="text" ng-model="form.emailaddress"> <br/><br/>
<textarea rows="3" cols="25" ng-model="form.textareacontent"></textarea>
<br/><br/>
<input type="radio" ng-model="form.gender" value="female" />Female ...
<input type="radio" ng-model="form.gender" value="male" />Male <br/>
<br/><br/>
<input type="checkbox" ng-model="form.member" value="5"/> Already a member
<br/><br/>
<input type="file" ng-model="form.file_profile" id="file_profile"><br/>
<input type="file" ng-model="form.file_avatar" id="file_avatar">
<br/><br/>
<!-- <button ng-click="save()" >Save</button> -->
<input type="submit" ngClick="Submit" >
</form>
</div>
My ng-app code...
var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {
var formData = {
firstname: "default",
emailaddress: "default",
textareacontent: "default",
gender: "default",
member: false,
file_profile: "default",
file_avatar: "default"
};
$scope.save = function() {
formData = $scope.form;
};
$scope.submitForm = function() {
console.log("posting data....");
formData = $scope.form;
console.log(formData);
//$http.post('form.php', JSON.stringify(data)).success(function(){/*success callback*/});
};
});
I guess three questions I have from here on are...
How is my php file supposed to interact with this (how to I get the json string to an array in php file)?
How would I submit value of a checkbox when the checkbox is true?
I find a lot of information abotu using jQuery with Angular to submit images,, I see there is an image object in this submission already,, how do I retrieve that data? What are considerations to include with images?
I am willing to take any clear and concise information and assemble a good learning example for everyone...
My fiddle
WARNING This is for Angular 1.x
If you are looking for Angular (v2+, currently version 8), try this answer or the official guide.
ORIGINAL ANSWER
I have rewritten your JS fiddle here: http://jsfiddle.net/YGQT9/
<div ng-app="myApp">
<form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">
First name: <br/><input type="text" name="form.firstname">
<br/><br/>
Email Address: <br/><input type="text" ng-model="form.emailaddress">
<br/><br/>
<textarea rows="3" cols="25">
Describe your reason for submitting this form ...
</textarea>
<br/>
<input type="radio" ng-model="form.gender" value="female" />Female
<input type="radio" ng-model="form.gender" value="male" />Male
<br/><br/>
<input type="checkbox" ng-model="form.member" value="true"/> Already a member
<input type="checkbox" ng-model="form.member" value="false"/> Not a member
<br/>
<input type="file" ng-model="form.file_profile" id="file_profile">
<br/>
<input type="file" ng-model="form.file_avatar" id="file_avatar">
<br/><br/>
<input type="submit">
</form>
</div>
Here I'm using lots of angular directives(ng-controller, ng-model, ng-submit) where you were using basic html form submission.
Normally all alternatives to "The angular way" work, but form submission is intercepted and cancelled by Angular to allow you to manipulate the data before submission
BUT the JSFiddle won't work properly as it doesn't allow any type of ajax/http post/get so you will have to run it locally.
For general advice on angular form submission see the cookbook examples
UPDATE The cookbook is gone. Instead have a look at the 1.x guide for for form submission
The cookbook for angular has lots of sample code which will help as the docs aren't very user friendly.
Angularjs changes your entire web development process, don't try doing things the way you are used to with JQuery or regular html/js, but for everything you do take a look around for some sample code, as there is almost always an angular alternative.
Sending data to some service page.
<form class="form-horizontal" role="form" ng-submit="submit_form()">
<input type="text" name="user_id" ng-model = "formAdata.user_id">
<input type="text" id="name" name="name" ng-model = "formAdata.name">
</form>
$scope.submit_form = function()
{
$http({
url: "http://localhost/services/test.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.formAdata)
}).success(function(data, status, headers, config) {
$scope.status = status;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}
I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:
Angularjs - Form Post Data Not Posted?
The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.
I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().
If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.
var app = angular.module( "myApp", [] );
app.controller( "myCtrl", ["$scope", function($scope) {
$scope.submit_form = function(formData) {
$scope.formData = formData;
console.log(formData); // object
console.log(JSON.stringify(formData)); // string
$scope.form = {}; // clear ng-model form
}
}] );
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<form ng-submit="submit_form(form)" >
Firstname: <input type="text" ng-model="form.firstname" /><br />
Lastname: <input type="text" ng-model="form.lastname" /><br />
<hr />
<input type="submit" value="Submit" />
</form>
<hr />
<p>Firstname: {{ form.firstname }}</p>
<p>Lastname: {{ form.lastname }}</p>
<pre>Submit Form: {{ formData }} </pre>
</div>
Codepen
I'm only starting to dive into angular.js and have found this issue that I can't seem to get around. Consider this simple code:
<input type="text" ng-model="test">
<input type="text" value="{{test}}">
When I write in the first field, the second one is updated nicely. When I write in the second field and then go back to the first one, the binding is not updated anymore. Interestingly though, the HTML attribute value does get updated - it's just not displayed.
Equivalent (at least roughly) code in vanilla javascript does not suffer from this:
<input type="text" id="model">
<input type="text" id="binding">
<script>
var model = document.getElementById("model");
var binding = document.getElementById("binding");
model.addEventListener("keyup",function() {
binding.value = model.value;
});
</script>
Here's a fiddle for you to test both: http://jsfiddle.net/Q6b5k/
Any idea why this happens when using angular.js and how to fix this?
[EDIT] Judging by the initial replies, it appears I have not made it clear. I do not want the second field to update the first one. The binding is to be one-way only, e.g. to allow filtering or even manual corrections (such as automatic creation of a URL alias in a blog post creation form). http://jsfiddle.net/Q6b5k/1/
The value attribute is only used when rendering the initial HTML. After the page load, everything else happens in the Angular Event Loop and therefore you need to do something that event loop can pick up. You can use ng-change for what you are looking to do:
<input type="text" ng-model="test" ng-change="test2=test.toLowerCase();" />
<input type="text" ng-model="test2"">
This happens because {{value}} does not create a binding, it is used for interpolation.
The simplest solution is to use ng-model in both the fields
<div ng-app>
Angular.js:<br>
<input type="text" ng-model="test">
<input type="text" ng-model="test">
</div>
Demo: Fiddle