ng-click not working on submit button - angularjs

I am learning how to use AngularJS, and I can't get a custom ng-click function to work. What I want to do is fire a $http.post request that contains data from my forms ($scope.email, $scope.username, $scope.password). So far I've tried only passing in email, but nothing happens when I click the submit button (there is no POST request fired, I am checking this with firebug). I tried passing it directly as $scope.email, or as a variable (as shown below).
I have a main page (index.html), that uses ng-view to load html using ngRoute. This the the route code:
.when('/register', {
templateUrl: 'views/register.html',
controller: 'RegisterCtrl'
})
Here is my register.html:
<div class="container">
<div class="col-xs-2 col-sm-3 col-md-4"></div>
<div class="col-xs-8 col-sm-6 col-md-4">
<h1>Sign Up:</h1>
<form>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" ng-model="email">
</div>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" ng-model="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" ng-model="password">
</div>
<button type="submit" class="btn btn-primary col-xs-5" ng-click="register">Sign up</button>
<div class="col-xs-2"></div>
<button class="btn btn-info col-xs-5">Go to log in</button>
</form>
</div>
</div>
and my controller:
'use strict';
angular.module('angularApp')
.controller('RegisterCtrl', function ($scope, $http) {
$scope.email = '';
$scope.username = '';
$scope.password = '';
$scope.register = function() {
// TODO ADD VALIDATION
var email = $scope.email;
var username = $scope.username;
var password = $scope.password;
// $http request
$http.post('http://localhost/PTC/API/new_user.php', email).
success(function(data) {
console.log(data);
}).
error(function(data) {
console.log(data);
});
};
});

it should have function () brackets to call function like ng-click="register()"
OR for more better way rather than using ng-click on form you could replace it with ng-submit directive
Markup
<form name="myForm" ng-click="register()">
...fields here..
<button type="submit" class="btn btn-primary col-xs-5">Sign up</button>
<div class="col-xs-2"></div>
<button class="btn btn-info col-xs-5">Go to log in</button>
</form>
Additionally you need to give form name to your form, so that you could get better controller over form validation.

Related

angularjs form inside bootstrap modal popup

I have a form inside a bootstrap modal.But I can't able to get the values of form on controller side with scope variable.
https://plnkr.co/edit/FjKXUpoBDdvQqomI97ml?p=preview
My original code has another problem also. when I click on submit button it will refresh the whole page and submit function is not executing.
My form:
<div class="modal-body">
<form class="form-horizontal" name="contact" ng-submit="contactForm()">
<div class="form-group">
<label class="col-lg-3 control-label">Name* :</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="name" name="_name" ng-model="_name" > </div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email* :</label>
<div class="col-lg-8">
<input class="form-control" type="email" id="email" name="_email" ng-model="_email" required> </div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Mobile* :</label>
<div class="col-lg-8 row">
<div class="col-lg-4">
<input type="text" class="form-control" ng-model="_cc" placeholder="+91" name="_cc"> </div>
<div class="col-lg-8">
<input class="form-control" type="text" ng-model="_mobile" maxlength="10" ng-pattern="/^[0-9]{5,10}$/" id="mobile" name="_mobile"></div>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Message :</label>
<div class="col-lg-8">
<textarea class="form-control" rows="2" name="_condition" ng-model="_condition"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-7 col-lg-5">
<button type="submit" class="btn btn-primary" id="contactSubmit" >Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div></div>
</form>
</div>
Controller:
$scope.contactForm = function(){
console.log($scope._condition,$scope._name,$scope._email,$scope._cc,$scope._mobile);
};
You are opening the modal using plain jQuery approach which is not going to work in Angular, because opened modal is not connected to Angular application, so it doesn't know that modal has to be handled, HTML parsed, etc.
Instead you should use directives properly, or in case of modal dialog you can simply use existent ones, like Angular UI project, which brings ready Bootstrap directives for Angular. In your case you need $modal service and inject the $http service to have your data posted.
Here is the working plunker using angular-ui bootstrap.
PLUNKER:https://plnkr.co/edit/rjtHJl0udyE0PTMQJn6p?p=preview
<html ng-app="plunker">
<head>
<script src="https://code.angularjs.org/1.2.18/angular.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
<script src="script.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<form ng-submit="submit()">
<div class="modal-body">
<label>Email address:</label>
<input type="email" ng-model="user.email" />
<label>Password</label>
<input type="password" ng-model="user.password" />
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
<input type="submit" class="btn primary-btn" value="Submit" />
</div>
</form>
</script>
<button class="btn" ng-click="open()">Open Modal</button>
</div>
</body>
</html>
JS:
angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log,$http) {
$scope.user = {
email: '',
password: null,
};
$scope.open = function () {
$modal.open({
templateUrl: 'myModalContent.html', // loads the template
backdrop: true, // setting backdrop allows us to close the modal window on clicking outside the modal window
windowClass: 'modal', // windowClass - additional CSS class(es) to be added to a modal window template
controller: function ($scope, $modalInstance, $log, user) {
$scope.user = user;
$scope.submit = function () {
$log.log('Submiting user info.'); // kinda console logs this statement
$log.log(user);
$http({
method: 'POST',
url: 'https://mytesturl.com/apihit',
headers: {
"Content-type": undefined
}
, data: user
}).then(function (response) {
console.log(response);
$modalInstance.dismiss('cancel');
}, function (response) {
console.log('i am in error');
$modalInstance.dismiss('cancel');
});
//$modalInstance.dismiss('cancel'); // dismiss(reason) - a method that can be used to dismiss a modal, passing a reason
}
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
resolve: {
user: function () {
return $scope.user;
}
}
});//end of modal.open
}; // end of scope.open function
};

Angular model not injecting rest call when trying to UPDATE

So basically I am very new to angular and node so go easy on me. I have been building a REST API for a profile site and it obviously requires updating of posts. I have GET, DELETE and CREATE working but stuck with trying to get the current post object (from stateParams) to inject into the editor.
// Uses sateParams to get object id
.controller('EditPostCtrl', ['$scope', 'Post',
'$stateParams', '$state', function($scope, Post,
$stateParams, $state) {
$scope.action = 'Edit';
$scope.isDisabled = true;
$scope.post = Post.findById({ id: $stateParams.id })
.$promise
}])
<h1>Post Editor</h1>
<form name="form" ng-submit="submitForm()">
<div class="form-group">
<!-- If Error -->
<!-- Blog Title -->
<label>Title:</label>
<input type="text" class="form-control" placeholder="Example Title" autocomplete="off" required ng-model="post.title"></input>
<br />
<!--
<label>Author:</label>
<input type="text" class="form-control" autocomplete="off" placeholder="{{ author }}" required ng-model="post.author"></input>
<br />
-->
<!-- Date -->
<label>Date:</label>
<input type="date" class="form-control" required ng-model="post.date"></input>
<br />
<!-- Post Content -->
<label>Blog content:</label>
<div ng-controller="editorCtrl">
<textarea type="text" class="ck-editor" autocomplete="off" required ng-model="post.content"></textarea>
</div>
<div class="pull-right buttonspacer">
Cancel
<button class="btn btn-default btn-lg">{{ action }}</button>
</div>
</div>
</form>
.controller("EditPostCtrl", function($scope,$http){
$scope.submitForm = function(id) {
$http.post('/api/postid/' + id)
.success(function(data) {
$scope.action = 'Edit';
$scope.isDisabled = true;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
});
in your angularjs,
you can use ng-click e.g.
<button class="btn btn-default btn-lg" ng-click="submitForm(post._id)">{{ action }}</button>
can you try this

Form input is undefined

Why the name and password are undefined?
I've used ng-model on them...
<form class="login" name="form">
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="name">Name: </label>
<input type="text" ng-model="name" id="name" class="form-control" placeholder="Nitzan">
</div>
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="password">Password: </label>
<input type="password" ng-model="password" id="password" class="form-control" placeholder="1234">
<p class="help-block" ng-if="isInvalidLogin">Name or password are wrong!</p>
</div>
<button type="submit" class="btn btn-block btn-lg btn-success login-btn" ng-click="login()">Login</button>
</form>
In the controller:
$scope.login = function () {
usersService.get($scope.name, $scope.password).then(function success(result){
$scope.currentUser = result;
}, function error() {
$scope.isInvalidLogin = true;
});
};
See the plunker:
http://plnkr.co/edit/QD3vtil3w9pd4d1TGl9v?p=preview
Your problem is because of ng-if directive which is creating child scope from current scope. Hence $scope.name & $scope.password is undefined inside $scope.login function.
I'd suggest you do create one object for user which is initially blank like user={} or you can do this on html using ng-init, then put it inside of mainController so that it can directly access by the parent without doing $parent. notation.
And place name and password inside user object.
HTML
<div ng-init="user={}">
<div class="container login-div" ng-if="!currentUser">
<form class="login" name="form" ng-submit="login()">
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="name">Name:</label>
<input type="text" ng-model="user.name" id="name" class="form-control" placeholder="Nitzan">
</div>
<div class="form-group" ng-class="{'has-error': isInvalidLogin}">
<label for="password">Password:</label>
<input type="password" name="test" ng-model="user.password" id="password" class="form-control" placeholder="1234">
<p class="help-block" ng-if="isInvalidLogin">Name or password are wrong!</p>
</div>
<button type="submit" class="btn btn-block btn-lg btn-success login-btn">Login</button>
</form>
</div>
</div>
CODE
$scope.login = function () {
alert("Name "+ $scope.user.name +"& password is " +$scope.user.password)
//usersService.get($scope.name, $scope.password).then(function success(result){
// $scope.currentUser = result;
//}, function error() {
// $scope.isInvalidLogin = true;
//});
};
Working Plunkr here.
Update
Otherwise you need to add change your ng-model to refer this scope to parent scope like
HTML
For name ng-model="$parent.name"
For password ng-model="$parent.password"
CODE
$scope.login = function () {
alert("Name "+ $scope.name +"& password is " +$scope.password)
//usersService.get($scope.name, $scope.password).then(function success(result){
// $scope.currentUser = result;
//}, function error() {
// $scope.isInvalidLogin = true;
//});
};
Plunkr Here
Hope this could help you. Thanks.

Angularjs form submition with post and catching response , redirecting different view or displaying response on the same the view

I am new to angularjs, I am trying to use $http.post and want display the response in the same view or different view by using ng-show directive.
Control is coming to success and displaying divsion and immediatly disappearing. Please help me.
Thanks in advance.
var myapp = angular.module('registrationApp', [ 'ngRoute' ]);
// create angular controller
myapp.controller('mainController', function($scope, $http) {
$scope.regStatus =false;
// function to submit the form after all validation has
// occurred
$scope.submitForm = function() {
user = {
"type" : "admin",
"emailid" : $scope.user.email,
};
var res = $http.post('/fosiness-web/services/user/registeruser', user);
res.success(function(data, status, headers, config) {
alert("Success : " + JSON.stringify({
data : data }));
debugger;
$scope.mydata = data;
$scope.regStatus = true;
});
res.error(function(data, status, headers, config) {
alert("failure message: " + JSON.stringify({
data : data
}));
});
}
});
<div class="container" style="background-color: #E8E8E8;"
ng-app="registrationApp" ng-controller="mainController">
...................
<div class="alert alert-success" ng-show="regStatus">
× Success <strong ng- model="user.message.description">{{mydata}} {{regStatus}}</strong>
</div>
<form id="registrationForm" method="post" method="POST"
novalidate
class="form-horizontal registerForm"
data-bv-feedbackicons-valid="glyphicon glyphicon-ok"
data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
data-bv-feedbackicons-validating="glyphicon glyphicon-refresh">
<div class="form-group">
<label class="col-sm-3 control-label">Email-Id</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="email"
ng-model="user.email" data-bv-notempty="true"
data-bv-notempty-message="The email address is required and cannot be empty"
data-bv-emailaddress="true"
data-bv-emailaddress-message="The email address is not a valid" />
</div>
......................
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<!-- Do NOT use name="submit" or id="submit" for the Submit button -->
<button type="submit" class="btn btn-info"
ng-click="submitForm()">Sign up</button>
<button type="reset" class="btn btn-warning">Reset</button>
</div>
</div>
</form>
</div>

what is happening to my angular scope?

I am using angularstrap modal service to open a login modal on any page when login is required. I open one like this:
var scope = {'foo': 'bar'};
var myOtherModal = $modal({scope: scope, template: 'modal/login.html', show: false});
the login.html contains the modal markup but it also has a controller bound to it:
<div ng-controller="SignInController" class="modal" tabindex="-1" role="dialog">
<input ng-modal="foo"/>
In the controller code, how do I get access to the foo prop on the scope that I am passing in?
What is happening to my scope? Is a scope object created by $modal the one and the same that is used by the controller? It appears that its not the case.
What is the best way to solve this problem? (Ability to open a login dialog from anywhere and have control over its scope from the controller)
Thanks
Think of opening a modal as a function call... where you pass data in and get data back. It's not the ONLY way to approach it but I think it's a clean way to approach it.
I generally follow this pattern, giving the modal it's own controller & passing data in & getting data back by passing it into the promise:
var ModalController = function($scope, $modalInstance, input) {
$scope.input = input;
var output = {
username: "",
password: ""
};
$scope.ok = function () {
$modalInstance.close($scope.output);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
$scope.openModal = function(data) {
var modalInstance = $modal.open({
templateUrl: 'popupDialog.tpl.html',
controller: ['$scope', '$modalInstance', 'input', ModalController],
resolve: {
input: function() {
return data;
}
}
});
modalInstance.result.then(function(output) {
// TODO: do something with the output.username & output.password...
// call Login Service, etc.
});
};
EDIT: Adding popup html...
<form class="form-horizontal">
<div class="modal-header">
<h3>Please Log In</h3>
</div>
<div class="modal-body">
<form name="form" class="form-horizontal">
<div class="row">
<label class="col-sm-3 text-info control-label" for="inputUsername">Username</label>
<input class="col-sm-8 form-control input-sm" type="text" id="inputUsername" name="inputUsername" ng-model="output.username" />
</div>
<div class="row">
<label class="col-sm-3 text-info control-label" for="inputPassword">Password</label>
<input class="col-sm-8 form-control input-sm" type="text" id="inputPassword" name="inputPassword" ng-model="output.password" />
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-sm btn-primary" type="submit" ng-click="ok()">Ok</button>
<button class="btn btn-sm btn-warning" ng-click="cancel()">Cancel</button>
</div>
</form>

Resources