Submit form with angular - angularjs

I have the following Angular code
controller:
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.job = null;
vm.create = function (job) {
vm.job = job;
}
});
HTML:
<div ng-controller="MainCtrl as vm">
<span data-ng-bind="vm.job.position"></span>
<form name="form" data-ng-submit="vm.create(vm.job)">
<label for="position">Position</label>
<input id="position" name="vm.job.position" type="text" data-ng-model="vm.job.position" />
<button>Create</button>
</form>
</div>
But when I submit the form I don't see the Position value.
Any idea why?

Because
You forgot to add ng-app to the body or html element
You're using angular 1.0.8, which is completely obsolete, and doesn't support controller as.
Note that you don't even need to submit, since the job you're binding is already vm.job. Your create(vm.job) method call does nothing: it assigns vm.job to vm.job.

Related

form validation using angularjs

Im trying to validate my form, if the fields are valid then it should post the data to the DB if not prevent from posting the data to DB. when I submit the form Im getting an error TypeError: Cannot read property '$valid' of undefined, I don't know how to overcome it, need help in this.
html:
<form name="formvalidation">
<ion-view ng-controller="ValidationCheck">
<ion-content>
<div>
<strong>User:</strong> <br/>
<input ng-model="name" type="text" name="name" required/>
<ng-messages for="formvalidation.name.$error" ng-if="formvalidation.name.$invalid">
<div ng-messages-include="error/validation.html"></div>
<ng-messages>
</div>
</from>
<button ng-click="check()">
controller:
myApp.controller('ValidationCheck',function($scope, applicationService)
{
$scope.check=function(formvalidation){
var name={'name'=$scope.name};
$scope.submitted=true;
if(formvalidation.$valid){
applicationService.save(name,$scope.home);
}}});
Just change your if condition formvalidation.$valid to formvalidation
. because you already pass formvalidation.$valid in your function via ng-click
if(formvalidation){
...
...
...
}
Remove ng-click and add a ng-submit:
<form name="formvalidation" ng-submit="check()" novalidate>
Try this : ( controller before form )
<ion-view ng-controller="ValidationCheck">
<form name="formvalidation">
In your html you have:
<button ng-click="check(formvalidation.$valid)">
which calls the check function with either a true or false value (a boolean), depending on whether or not the form is valid.
In your controller you have the check function with the following if-statement:
if(formvalidation.$valid)
but formvalidation is a boolean (true or false)
I recommend removing the argument from check and simply access the formvalidation properties from the $scope variable.
so the html becomes
<button ng-click="check()">
and the controller becomes
$scope.check=function(){
var name={'name'=$scope.name};
$scope.submitted=true;
if($scope.formvalidation.$valid) {
applicationService.save(name,$scope.home);
}
}
<form> should come after controller declaration
<div ng-app="app">
<ion-view ng-controller="ValidationCheck">
<form name="formvalidation">
<ion-content>
var app = angular.module("app", []);
app.controller('ValidationCheck', function($scope) {
$scope.check = function(formvalidationBoolean) {
alert(formvalidationBoolean);
var name = {
'name': $scope.name
};
$scope.submitted = true;
if (formvalidationBoolean) {
//applicationService.save(name, $scope.home);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<ion-view ng-controller="ValidationCheck">
<form name="formvalidation">
<ion-content>
<div>
<strong>User:</strong>
<br/>
<input ng-model="name" type="text" name="name" required/>
<ng-messages for="formvalidation.name.$error" ng-if="formvalidation.name.$invalid">
<div ng-messages-include="templates/admin/validation.html"></div>
<ng-messages>
</div>
</from>
<button ng-click="check(formvalidation.$valid)">Submit</button>
</div>
You are sending boolean value "ng-click="check(formvalidation.$valid)", So your statement if(formvalidation.$valid){ inside controller is wrong.
And You need to change "=" to ":" in var name = {'name': $scope.name };

How to detect checkbox clicked in AngularJS?

I am using a javascript UI library as DHTMLX or YUI etc.
And I am using AngularJS to process dynamic page.
What I need is just simple.
UI code is
...
<Input type="checkbox" name="XXX" />
....
My.js
...
app.controller('XXXCtrl', function($scope){
$scope.$watch(???){
if (XXX) console.log("checkbox was checked!!!");
else console.log("checkbox was unchecked!!!");
????
};
})
I am new to AngularJS. Please help me!!!
You have to bind the value to the scope via ng-model. There is more detail in the documentation, but you can do something like that:
$scope.checkboxModel = true;
$scope.myAction = function () {
msg = $scope.checkboxModel ? 'checked' : 'unchecked';
console.log(msg);
};
And in your HTML file:
<form name="myForm" ng-controller="XXXCtrl">
<label>Value1:
<input type="checkbox" name="XXX" ng-model="checkboxModel" ng-change="myAction()">
</label><br/>
<tt>value1 = {{checkboxModel}}</tt><br/>
</form>
You can access to the window object using document.getElementById combined with ng-click event listener
var app = angular.module('myApp', []);
app.controller('appCtrl', function($scope) {
$scope.checker= function(e){
var chkBox = document.getElementById(e.target.id);
console.log(chkBox.checked)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp'>
<div ng-controller='appCtrl'>
<input type="checkbox" id="myCheckbox" name="myCheckbox" ng-click="checker($event)"/>
</div>
</div>

select option isn't adding object in ionic

I'm trying to add a mongoose object to another mongoose object using a select bar in a form. All the other key,value pairs insert correctly, even the checkbox bool, but the select-option combo won't save the I've done this before with no problem, but in ionic, it doesn't seem to want to work. Is there a work around or am I just messing something up in the code?
$scope.addProperty = function(prop){
console.log(prop);
Props.add(prop)
.then(function(res) {
console.log(res.data);
//window.location.reload();
})
.catch(function(error){
console.log(error);
});
};
<form method = "post" class="form-inline" role="form" action = "localhost:3000/managers/newApt">
<div class="form-group">
<label class="sr-only" >Tenants:</label>
<select ng-model="prop.tenants" class="column medium-3" ng-options="manager.name for manager in allManagers"> </select>
</div>
<div class="form-group">
<label class="sr-only">Address</label>
<input type="text" class="form-control" ng-model='prop.address'>
</div>
<button type="submit" class="btn btn-default" ng-click='addProperty(prop)'>Add Property</button>
</form>
try to use this video tutorial they use var controllerName = this, inside controller and reference methods and properties of the controller through var controllerName, for example this is a controller:
angular
.module('your-app-module')
.controller('ExampleController', function ($scope, $state) {
//This var is to bind methods and vars in view(html) to this specific controller
var ExmpleCtrl = this; //this is the var that is going to replace $scope
//NOTICE no $scope but rather ExmpleCtrl
ExmpleCtrl.goToState = function (state) {
$state.go(state);
};
});
Now in your html try:
<ion-view ng-controller="ExampleController as exmpleCtrl">
<ion-content>
<!-- notice how I use exmpleCtrl instead of $scope to access controller or to pass info -->
<div ng-click="exmpleCtrl.doSomething()">
</ion-view>
If you still have doubt check this short video (ignore it's for webstorm the way they bind the controller to the a variable inside controller referenced to this is what is useful): http://blog.jetbrains.com/webstorm/2014/03/angularjs-workflow-in-webstorm/

Select some data and then persist to next controller/view in Angularjs

I am bringing in some simple data via a service that uses angular-resource like so:
angular.module('InvoiceService',
['ngResource'])
.factory('InvoiceService', function ($resource) {
return $resource('data.json');
})
.controller("DashboardListCtrl", function (InvoiceService) {
var vm = this;
InvoiceService.query(function (data) {
vm.invoices = data;
});
vm.submit = function (form) {
console.log(form)
};
});
And the html:
<form name="invoices" role="form" novalidate>
<ul>
<li ng-repeat="invoice in vm.invoices">
<input type="checkbox" id="{{'id-' + $index}}" />
<p><strong>Order:</strong></p>
<p>{{invoice.order}}</p>
</li>
<input type="submit" value="Continue" ng-click="vm.submit(invoices)" />
</ul>
</form>
Everything works fine; the data is displays in the view as expected.
The question:
What I'd like to do is be able to select a checkbox, grab the bit of data associated with that checkbox, and pass it along to the next controller/view on submit. How can I do this?
So, what do I do next? Am I on the right track?
**EDIT: added all angular code to help clarify
Posting answer as reply too big to be useful.
You should be using $scope to isolate the controller's data from the rest of the page.
Read up about ng-model http://docs.angularjs.org/api/ng/directive/ngModel and how to use it to two-way-bind checkbox value to a controller variable. No need to use theFormName if you call $scope.submit = function() { } as your ng-model variable will be available in $scope already.
angular.module('InvoiceService',
['ngResource'])
.factory('InvoiceService', function ($resource) {
return $resource('data.json');
})
.controller("DashboardListCtrl", function ($scope, InvoiceService) {
InvoiceService.query(function (data) {
$scope.invoices = data;
});
$scope.submit = function () {
// FIXME to access a property of each $scope.invoices
console.log('checkbox1=' + $scope.invoices[0].checkbox1);
};
});
Then the HTML:
<form role="form" novalidate ng-controller="DashboardListCtrl"><!-- EDIT: added ng-controller=, remove name= -->
<ul>
<li ng-repeat="invoice in invoices"><!-- EDIT: remove 'vm.' -->
<input type="checkbox" id="{{'id-' + $index}}" ng-model="invoice.checkbox1" /><!-- EDIT: added ng-model= -->
<p><strong>Order:</strong></p>
<p>{{invoice.order}}</p>
</li>
<input type="submit" value="Continue" ng-click="submit()" /><!-- EDIT: remove 'vm.' -->
</ul>
</form>

AngularJS: How to trigger function call when a form field gets focus

I want my controller to perform some action when a user clicks in a form field (when the form field gets focus). How can I do this? See this plunker.
Here is my controller:
angular.module('myApp', [])
.controller('AppCtrl', ['$scope',
function($scope) {
$scope.field1 = "Default text";
$scope.focus = false;
$scope.formFieldJustGotFocus = function() {
$scope.focus = true;
// Do all the stuff I need to happen when the form has just gotten focus
}
}
]);
And here is the view:
<body ng-app="myApp" ng-controller="AppCtrl">
<h3>Testing</h3>
<p>I want to perform some action in the controller when a form field gets focus. How can I best achieve this?</p>
<form name="myForm">
<input type="text" name="field1" ng-model="field1">
</form>
<p>Form field has focus: {{focus}}</p>
</body>
You can use the ngFocus directive. The inverse is ngBlur.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<input type="text" ng-focus="isFocused = true" ng-blur="isFocused = false">
<p ng-if="isFocused">Focus !</p>
</div>
<input type="text" name="field1" ng-model="field1" ng-focus="formFieldJustGotFocus()">
use like this ng-focus
Try ng-focus.
See more info:
https://docs.angularjs.org/api/ng/directive/ngFocus
use -> ng-focus
<input type="text" name="field1" ng-model="field1" ng-focus="formFieldJustGotFocus();">
this plunker
in the code he had written the function formFieldJustGotFocus(), but it was not bound to the focus event

Resources