I can't access ng-model from a controller [AngularJS] - javascript

I'm developing an e-commerce site for learnign purposes.
HTML:
<div class="container">
<form class="log-in-form" ng-controller="ControllerLogin">
<div class="form-group">
<label for="loginEmail">Email address</label>
<input type="email" class="form-control" id="loginEmail" placeholder="Email" ng-model="email">
</div>
<div class="form-group">
<label for="loginPass">Password</label>
<input type="password" class="form-control" id="loginPass" placeholder="Password" ng-model="password">
</div>
<button class="btn btn-default" ng-click="authenticate()">Login</button>
</form>
</div>
Angular javascript
app.controller('ControllerLogin', ['$scope', '$http', 'ServiceLogin', function ($scope, $http, ServiceLogin) {
$scope.authenticate = function () {
console.log($scope.email);
ServiceLogin.auth($scope.email, $scope.password)
.success(function (data) {
alert(data);
});
}
}]);
Every time I console.log the $scope.email, or password. It throws an error of undefined. I'm just starting on angular and I don't know why is not getting the models, I thinks my code is correct. Any help you can give I will be gratefull.

From Angular site:
Note that novalidate is used to disable browser's native form validation.
The value of ngModel won't be set unless it passes validation for the input field. For example: inputs of type email must have a value in the form of user#domain.
Reference: https://docs.angularjs.org/guide/forms
So the reason it may be blank is that it's not a valid email.
You can look at their demo for the email type and see it in action.
I recommend adding:
{{email}}
<br>
{{password}}
somewhere in your html within the controller's HTML scope for your own debugging.
Good luck.

Related

AngularJs scope params undefined [duplicate]

This question already has answers here:
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
(3 answers)
Closed 4 years ago.
I have just started learning AngularJS and I am trying to make this simple app with simple inputs, controllers and a firebase database.
Problem is, the $scope params userEmail and userPassword are always undefined in Signin() when I click the button.
HTML relevant code:
<body ng-app="indexApp">
...
<div class="row" ng-controller="loginCtrl">
<div class="hero-text-box">
<br>
<form>
<p class="p2"><label for="email">email</label></p>
<input ng-model="userEmail" id="email1" type="email"
name="email1" placeholder="email">
<p class="p2"><label for="password">pasword</label></p>
<input ng-model="userPassword" type="password" id="password"
name="password" placeholder="password" required>
<a class="btn btn-full" href="#" ng-click="Signin()">הכנס</a>
</form>
</div>
</div>
AngularJS javascript code:
var app = angular.module("indexApp", ["firebase"]); // using firebase
app.controller("loginCtrl", function($scope, $firebaseArray) // AngularJS
will auto add firebase
{
var ref = firebase.database().ref().child("users")
// create a synchronized array
$scope.users = $firebaseArray(ref)
$scope.Signin = function()
{
console.log($scope.userEmail) -- undefined!
....
If you want to use form with angularJS, you should follow angularjs form guide:https://docs.angularjs.org/guide/forms
In your case, you need to move signin() function to html form element.I created a jsfiddle based on your code: http://jsfiddle.net/sxwei123/ADukg/25254/
Hope this would help!
This might help
HTML
<body ng-app="indexApp">
...
<div class="row" ng-controller="loginCtrl">
<div class="hero-text-box">
<br>
<form>
<p class="p2"><label for="email">email</label></p>
<input ng-model="userdata.userEmail" id="email1" type="email"
name="email1" placeholder="email">
<p class="p2"><label for="password">pasword</label></p>
<input ng-model="userdata.userPassword" type="password" id="password"
name="password" placeholder="password" required>
<a class="btn btn-full" href="#" ng-click="Signin(userdata)">הכנס</a>
</form>
</div>
</div>
Controller
var app = angular.module("indexApp", ["firebase"]); // using firebase
app.controller("loginCtrl", function($scope, $firebaseArray) // AngularJS
will auto add firebase
{
var ref = firebase.database().ref().child("users")
// create a synchronized array
$scope.users = $firebaseArray(ref)
$scope.userdata = {};
$scope.Signin = function(data){
console.log(data) // you will get the object
}

AngularJS with ng-pattern in form does not send invalid field to server

I want to validate a text input in form, so the submit of the form could not be done until the input match a regular expression. But when I type a wrong field value and I clik submit the form is submitted but the input value is not sent to the server. I want the same behaviour as with HTML5 required Attribute. This is my code:
<div class="row">
<label class="col-sm-2 label-on-left">APN</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="apn" ng-model="Configure3gCtrl.configure3g.apn" ng-pattern="/^[a-zA-Z0-9-.]*$/" required/>
</div>
</div>
</div>
As i said in the comment [value not sent because when you pass the input with incorrect pattern the ng-model is undefined].
But we can use the form validation here as sample if our ng-model are invalid the form will disabled.
var app = angular.module("app", []);
app.controller("ctrl", ["$scope", "$filter", function($scope, $filter) {
$scope.submit = function() {
console.log($scope.object)
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<form name="form">
<label class="col-sm-2 label-on-left">APN</label>
<input type="text" name="apn" ng-model="object.apn" ng-pattern="/^[a-zA-Z0-9-.]*$/" required />
<button ng-click="submit()" ng-disabled="form.$invalid">submit</button>
</form>
</div>
Ideally, you should not send the invalid value to server, So you should disable\hide your submit button, but if you really require sending the invalid value as well to server, then from angularjs 1.3+ you have ng-model-options (Read Doc) directive which can help you.
Simply mark your text type input as ng-model-options="{allowInvalid: true }", It will persist the invalid values as well.
See Demo:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function MyCtrl($scope) {
$scope.submitt = function() {
alert($scope.Configure3gCtrl.configure3g.apn);
}
$scope.Configure3gCtrl = {
configure3g: {
apn: ""
}
}
});
<script src="https://code.angularjs.org/1.3.1/angular.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="frm" ng-submit="submitt()" class="row">
<label class="col-sm-2 label-on-left">APN</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="apn"
ng-model="Configure3gCtrl.configure3g.apn"
ng-model-options="{allowInvalid: true }"
ng-pattern="/^[a-zA-Z0-9-.]*$/" required/>
</div>
</div>
<input type="submit" value="submit" type="submit" />
</form>
</div>
also, Test with removing ng-model-options="{allowInvalid: '$inherit' }" from above code snippet then ng-model will be undefined, because it is invalid.

Custom password validation directive not applying

I'm working with AngularJS and I want to make a password confirmation field to check if both entries match. In order to do that, I'm using a custom directive from this tutorial: http://odetocode.com/blogs/scott/archive/2014/10/13/confirm-password-validation-in-angularjs.aspx.
For some reason, the matching checking doesn't give any result. When I enter different passwords, it still sees the fields as valid. I think I'm missing something about the usage of custom directives in AngularJS, but it's a bit confusing because I'm litterally taking the exact same code as in the tutorial.
I also checked related questions here on SO, but no luck either.
HTML:
<div ng-app="myApp">
<h1>Register!</h1>
<form name="registrationForm" novalidate>
<div class="form-group">
<label>User Name</label>
<input type="text" name="username" class="form-control" ng-model="registration.user.username" required />
<p ng-show="registrationForm.username.$error.required">Required<br/><br/></p>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" ng-model="registration.user.password" required />
<p ng-show="registrationForm.password.$error.required">Required<br/><br/></p>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirmPassword" class="form-control" ng-model="registration.user.confirmPassword" required compare-to="registration.user.password" />
<p ng-show="registrationForm.confirmPassword.$error.required">Required<br/><br/></p>
<p ng-show="registrationForm.confirmPassword.$error.compareTo">Passwords must match !</p>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Register!</button>
</div>
</form>
</div>
JS:
angular.module('myApp', [])
.directive('compareTo', function(){
return {
require: "ngModel",
scope: {
otherModelValue: "=compareTo"
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.compareTo = function(modelValue) {
return modelValue == scope.otherModelValue;
};
scope.$watch("otherModelValue", function() {
ngModel.$validate();
});
}
};
})
JSFiddle showing the problem: http://jsfiddle.net/ptb01eak/
Working Plunkr from the tutorial: http://plnkr.co/edit/FipgiTUaaymm5Mk6HIfn?p=preview
Thank you for your help!
The problem comes from your AngularJS version, I updated it in the jsfiddle to : AngularJS 1.5.6 (CDN link) and it works (new jsfiddle).

Convert HTML form into Angular POST request

I have this form in HTML and I am trying to convert it into a POST request using a frontend framework (either AngularJS or Angular2). The purpose of this form is to allow a client to subscribe to my wordpress blog. I am trying to convert it from PHP to Angular2 (if someone knows how to convert it to AngularJS I can convert to Angular2 from there). How would I do this? What would have to be in the body of the POST request vs query strings? I am having trouble understanding exactly what role each part of this form plays in the POST request.
EDIT: Just to clarify, I know how to use AngularJS and Angular2 and how to use the HTTP service in both of them. I am wondering how to convert the form into the body/query strings of the request.
<form action="/blog/" class="form-inline" role="form" method="POST" accept-charset="utf-8" id="subscribe-blog">
<!-- add hidden inputs for wordpress jetpack widget -->
<input type="hidden" name="action" value="subscribe" />
<input type="hidden" name="source" value="http://www.mywebsite.com/blog/" />
<input type="hidden" name="sub-type" value="widget" />
<input type="hidden" name="redirect_fragment" value="blog_subscription-2" />
<label class="sr-only" for="exampleInputEmail">Email address</label>
<input type="email" class="form-control wide" id="exampleInputEmail" placeholder="Enter email address">
<button type="submit" name="jetpack_subscriptions_widget" class="btn btn-submit">Subscribe</button>
</form>
Would something along the lines of this be correct?
postForm() {
var body = {
action: 'subscribe',
source: 'http://www.mywebsite.com/blog/',
sub-type: 'widget',
redirect_fragment: 'blog_subscription-2',
email: 'clientEmailAddress#gmail.com', // don't think this is right
// not sure what to do with `jetpack_subscriptions_widget` attribute on the submit button either
};
return this.http.post(`http://www.mywebsite.com/blog/`, body)
.map(res => res.json())
.toPromise()
.then(data => {
return data;
});
}
You need to include angular.min.js and script.js
html
<body ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="name" />
<input type="submit" value="Send" ng-click="send(name)"/>
</body>
angular js code:
script.js
angular.module('myApp', [])
.controller('myCtrl', ['$scope', '$http', funtion($scope, $http){
$scope.name = ""; // intially the input field is empty. As you type in the input field, the value will be updated here.
$scope.send = function(name){
alert(name);
var url = $scope.name; // try to enter an url
$http.get(url).then(function Success(res){
// here you can do anything with res
}, function Error(err){
alert(error);
})
}
}]);
Using angular, you split the application in parts:
view (html)
process some validations, etc (controller)
and do some model logic processing (service).
If you want to make the http request completely with angular to an endpoint (backend service, REST, or any other), usually in this case:
You use ng-model for each input field you need to send in the request, something like <input type="text" ng-model="val">. In your case your html would be something like:
html
<form ng-submit="send()" class="form-inline" role="form" accept-charset="utf-8" id="subscribe-blog">
<!--no need of 'action' attribute in the form since the post will be done using angular-->
<!-- add hidden inputs for wordpress jetpack widget -->
<input type="hidden" name="action" value="subscribe" ng-model="subscribe"/>
<input type="hidden" name="source" value="http://www.mywebsite.com/blog/" ng-model="source"/>
<input type="hidden" name="sub-type" value="widget" ng-model="widget" />
<input type="hidden" name="redirect_fragment" value="blog_subscription-2" ng-model="redirect_fragment"/>
<label class="sr-only" for="exampleInputEmail">Email address</label>
<input type="email" class="form-control wide" id="exampleInputEmail" placeholder="Enter email address" ng-model="email">
<button type="submit" name="jetpack_subscriptions_widget" class="btn btn-submit">Subscribe</button>
</form>
Then in your controller you can process all your ng-model if needed and then pass those values to a (angular) service like this
//....angular controller
function send(){
//..collect params using the ng-models
var params = [];
params['email'] = $scope.email; //here you define 'email' as the name of the param received by the webservice as input !!!
myService.sendValues(params).then(function(data){
})
}
...where you would finally send the values to the php service like code below:
//... angular service
function sendValues(params){
var url = "miendpointurl/subscribe";
//... at this pont in params you have all those params you named like 'email', 'subscribe' and so on
return $http.post(url, params).then(function(response){
return response.data;
},
function(responseOnError){
return responseOnError.data;
}
}
Angular will interact with the php service transparently to you and will give you back the server response.

POST is not getting current values from angular

In my view there are two forms (one is visible, second one is hidden). First one as action calls submit1() function in controller, that in turn will invoke document.getElementById('form2').submit(); Second form action has method POST that directly calls php.
Now I cannot get why if my submit1() looks like this:
function submit1()
{
// doesnt matter
$scope.first = 'this is my string'; // here I'm modifying variable from $scope1 that is directly in form2
document.getElementById('form2').submit(); // problem here!
// doesn't matter
}
It does not work as expected.
Basically, when form2 is sent, it still has a default value (not changed one).
Looks like it would not really change variable outside the scope of function submit1() or like POST would not accept this change. Anyone can tell me why it is like that?
Moreover I was previously using $http post method instead document.getElement().submit() and it works fine. So this seems to be weird.
I would appreciate any help in this matter.
Thank you!
Edit1: (adding more code to properly define what is a problem):
view:
<div class="container">
<div ng-hide="true" >
<form action="./order2.php" id="form2" method="POST">
<input type="text" name="username" value="{{username}}"/>
<input type="text" name="phone" value="{{phone}}"/>
<input type="text" name="address" value="{{address}}"/>
<input type="text" name="price" value="{{totalPrice}}"/>
<input type="text" name="email" value="{{email}}"/>
<input type="text" name="message" value="{{text}}"/>
<input type="submit"/>
</form>
</div>
<form novalidate id="contact-form" name="contactForm">
<a class="btn btn-success" ng-click="submit1()" href>
<i class="fa fa-check-circle-o fa-lg"></i>
{{ 'ID_ORDER_BUTTON' | translate:$root.currentLang }}
</a>
</form>
</div>
Controller:
Appcontrollers.controller('controller1', function($scope, $http, $rootScope, $timeout, $routeParams, $window, $location, databaseService, translationService, cartService, leatherService, $location) {
$scope.text="";
$scope.email="11111#2222.com";
$scope.price=0;
$scope.address= "add";
$scope.phone="1213131";
$scope.username="usera";
$scope.submit1 = function() {
$scope.price=999999999; // this looks like doesn't have effect.
document.getElementById('form2').submit();
}
}

Categories