angularjs form inside bootstrap modal popup - angularjs

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
};

Related

$modal is not open for the second time in Angularjs

$modal is called in the $ngonint hook. First time when controller loads, it works perfectly. But for the second time, it is not showing up when the controller loads.
Expectation:
Consider two controllers first and second.
Navigate to second controller from first controller by clicking link.
We need to show below modal when page loads whenever navigate to second controller page.
Actual Result:
For the first time, when it navigate to second controller, it showed the modal as expected. once go back to first page and come again to second controller, modal is not showed up.
Can anyone help me to solve this issue ? Thanks.
Below are the code sample:
Controller
$onInit() {this.showModal();} // Need to show modal when page loads
public showModal= function () {
var modalInstance = $modal.open({
template: ModalTemplate,
controller: [
'$scope',
'$modalInstance',
function ($scope, $modalInstance) {
$scope.answer = '';
$scope.close = function () {
$modalInstance.dismiss();
};
$scope.next = function () {
$modalInstance.close($scope.answer);
};
},
],
windowClass: 'open-account'
});
modalInstance.result.then((response) => {
console.log(response);
})
}
ModalTemplate.html
<div class="modal-header">
<button type="button" class="close" ng-click="close()" aria-hidden="true">
<fa-icon icon="times" prefix="fal" class="close-fa fa-lg"></fa-icon>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-4">
<div class="form-group radio-group-label">
<label class="control-label">
Click
</label>
</div>
</div>
<div class="col-xs-2">
<div class="form-group">
<label class="control-label" for="answer-yes">
<input type="radio" name="answer" ng-model="answer" value="yes"
id="answer-yes" />
Yes
</label>
</div>
</div>
<div class="col-xs-2">
<div class="form-group">
<label class="control-label" for="answer-no">
<input type="radio" name="answer" ng-model="answer" value="no"
id="answer-no" />
No </label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-success" ng-disabled="!answer" ng-click="next()">Next</button>
</div>

Popup or modal in angularjs when clicked on login button

i want to do something like this: When i fill in the deatils i.e name and password and click on login it should display the details With welcome message(in modal or popup in angular) that i have filled in the textbox . it should be simple. Can anyone help me with that. I had a look in UI bootstrap modal but i am not getting anything from that.
<div ng-controller="logincontroller">
<div class="container-fluid">
<form action="" method="" class="register-form">
<div class="row">
<div class="col-md-4 col-sm-4 col-lg-4">
<label for="firstName">NAME</label>
<input name="firstName" minlength="3" maxlength="15" required class="form-control firstname" type="text" >
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4 col-lg-4">
<label for="password">PASSWORD</label>
<input name="password" required class="form-control password" type="password" >
</div>
</div>
<hr>
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-6 col-lg-6">
<button class="btn btn-default regbutton" ng-click="open()">Login</button>
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">No</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
my login.js file
var mymodule=angular.module("mymodule");
mymodule.controller("logincontroller",function($scope,$modal)
{
var modalInstance = $modal.open({
backdrop:'static',
keyboard:false,
controller: function($scope, $modalInstance) {
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
$scope.ok = function () {
$modalInstance.close();
};
}
});
})
i am getting error like this
Error: $injector:unpr
Unknown Provider
Unknown provider: $modalProvider <- $modal <- logincontroller
Check this answer. It might help you out.
var app = angular.module('angularModal', ['ngAnimate', 'ui.bootstrap']);
app.controller('ModalDemoCtrl', function ($scope, $uibModal, $log) {
$scope.open = function (size) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
firstName: function () {
return $scope.firstName;
}
}
});
};
});
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.
app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, firstName) {
setTimeout(function() {
$scope.$apply(function() {
$scope.firstName = firstName;
})
}, 1);
$scope.ok = function () {
$modalInstance.close($scope.firstName);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
<!DOCTYPE html>
<html data-ng-app="angularModal">
<head>
<link data-require="bootstrap-css#3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.0.js"></script>
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
Welcome {{firstName}}
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>
</script>
<div class="container-fluid">
<form method="" class="register-form">
<div class="row">
<div class="col-md-4 col-sm-4 col-lg-4">
<label for="firstName">NAME</label>
<input name="firstName" minlength="3" maxlength="15" required class="form-control firstname" type="text" ng-model="firstName">
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4 col-lg-4">
<label for="password">PASSWORD</label>
<input name="password" required class="form-control password" type="password" >
</div>
</div>
<hr>
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-6 col-lg-6">
<button class="btn btn-default regbutton" ng-click="open()">Login</button>
</div>
</div>
</form>
</div>
</body>
</html>

external template (templateURL) in Angular directive is not working

I'm trying to create an accordion on button click using AngularJS directive. I have external template for creating accordion. But I couldn't get it working. Here is the code:
Directive:
(function() {
'use strict';
angular.module('accountApp')
.directive('addSubsite', addSubsite);
function addSubsite ($compile, $templateRequest){
var ddo = {
restrict: 'A',
link: function(scope, element) {
element.bind("click", function(e){
$templateRequest("addSubsiteTemplate.html").then(function(html){
var template = angular.element(html);
$element.append(template);
$compile(template)(scope);
$element.find(".add-subsites").append(template);
});
});
}
};
return ddo;
}
})();
index.html
<button add-subsite type="button" class="btn btn-primary pull-right margin10-b"id="aid-addSubSitebtn">Add Sub-Site</button>
<accordion>
<accordion-group>
<div class="accordion-heading header">
<a class="accordion-toggle" id="primary__site__address" data-toggle="collapse" href="#primary__site">
<h4><span class="pull-left"><i class="icon-minus"></i></span>Business Name (Primary Site)</h4></a>
</div>
<div class="form-group">
<label for="exampleInputName2">Name</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="Jane Doe">
</div>
<div class="form-group">
<label for="exampleInputEmail2">Email</label>
<input type="email" class="form-control" id="exampleInputEmail2" placeholder="jane.doe#example.com">
</div>
<button type="submit" class="btn btn-default">Send invitation</button>
</accordion-group>
</accordion>
Template.html
<accordion>
<accordion-group>
<div class="accordion-heading header">
<a class="accordion-toggle"data-toggle="collapse" href="#subsite__site">
<h4><span class="pull-left"><i class="icon-minus"></i></span>Business Name (SubSite)</h4></a>
</div>
<div class="form-group">
<label for="exampleInputName2">Name</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="Jane Doe">
</div>
<div class="form-group">
<label for="exampleInputEmail2">Email</label>
<input type="email" class="form-control" id="exampleInputEmail2" placeholder="jane.doe#example.com">
</div>
<button type="submit" class="btn btn-default">Send invitation</button>
</accordion-group>
</accordion>
I changed my approach Here is the sample https://jsfiddle.net/2u7aLg5c/
angular.module('testApp',[])
.controller('TestController', function(){
const vm = this;
vm.inputs=[{}];
vm.myInput = [];
vm.add = function(){
vm.inputs.push({})
}
})

Angular validation directive not working properly

I am using custom angular directive for showing validation. Directive code is as below
angularFormsApp.directive('showErrors',['$timeout', function ($timeout) {
return {
restrict: 'A',
require: '^form',
link: function (scope, el, attrs, formCtrl) {
// find the text box element, which has the 'name' attribute
var inputEl = el[0].querySelector("[name]");
// convert the native text box element to an angular element
var inputNgEl = angular.element(inputEl);
// get the name on the text box so we know the property to check
// on the form controller
var inputName = inputNgEl.attr('name');
var helpText = angular.element(el[0].querySelector(".help-block"));
// only apply the has-error class after the user leaves the text box
inputNgEl.bind('blur', function () {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
helpText.toggleClass('hide', formCtrl[inputName].$valid);
});
scope.$on('show-errors-event', function () {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
});
scope.$on('hide-errors-event', function () {
$timeout(function () {
el.removeClass('has-error');
}, 0, false);
});
}
}
}]);
and Html is as below
<div class="container" id="login-form">
<img src="assets/img/logo-big.png">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h2>Login Form</h2>
</div>
<div class="panel-body">
<form name="loginForm" class="form-horizontal" novalidate>
<div class="form-group mb-md" show-errors>
<div class="col-xs-12">
<div class="input-group">
<span class="input-group-addon">
<i class="ti ti-user"></i>
</span>
<input type="text" class="form-control" placeholder="Username" autocomplete="Off" ng-required="true" name="username" autofocus ng-model="loginUser.username">
</div>
<span class="help-block" ng-if="loginForm.username.$error.required">Username is required</span>
</div>
</div>
<div class="form-group mb-md" show-errors>
<div class="col-xs-12" >
<div class="input-group">
<span class="input-group-addon">
<i class="ti ti-key"></i>
</span>
<input type="password" class="form-control" placeholder="Password"
name="password"
ng-model="loginUser.password" autocomplete="Off"
ng-required="true">
</div>
<span class="help-block" ng-if="loginForm.password.$error.required">Password is required</span>
</div>
</div>
<div class="form-group mb-n">
<div class="col-xs-12">
Forgot password?
<div class="checkbox-inline icheck pull-right p-n">
<label for="">
<input type="checkbox"></input>
Remember me
</label>
</div>
</div>
</div>
</form>
</div>
<div class="panel-footer">
<div class="clearfix">
Register
Login
</div>
</div>
</div>
</div>
</div>
</div>
Controller code :
var loginController = function ($scope, $window, $routeParams, $uibModal, $location, $filter, $rootScope, DataService, SharedProperties) {
$rootScope.bodylayout = 'focused-form animated-content';
$scope.loginUser = {
username: "",
password:""
}
$scope.load = function () {
//getAppointmentInfo();
};
$scope.SubmitLoginForm = function () {
$scope.$broadcast('show-errors-event');
if ($scope.loginForm.$invalid)
return;
}
}
angularFormsApp.controller("loginController", ["$scope", "$window", "$routeParams", "$uibModal", "$location", "$filter", "$rootScope", "DataService", "SharedProperties", loginController]);
Now When I open form below input control validation span is displaying by default . When I click on Login button then its showing in red and working fine.
problem is it shouldn't show by default when Page is opend.. Please see image below
Instead of this
loginForm.password.$error.required
try this
(loginForm.$submitted || loginForm.username.$dirty) && loginForm.password.$error.required
Take a look at the ng-messages directive. Its fairly elegant. Example:
<form name="myForm">
<input type="text" ng-model="field" name="myField" required minlength="5" />
<div ng-messages="myForm.myField.$error">
<div ng-message="required">You did not enter a field</div>
<div ng-message="minlength">The value entered is too short</div>
</div>
</form>
You can then combine it with any form validation. Just place the error messages from the validators onto the elements $error object and they are automatically rendered in your UI.
I ended up here as part of my search for an issue. In my case I was using a directive with a changing minimum value like this:
ngOnChanges(changes: SimpleChanges) {
if (changes.minDate && this.control) {
this.control.updateValueAndValidity({ onlySelf: true });
}
}
This means that the form will not be updated, I removed onlySelf and it worked correctly.
this.control.updateValueAndValidity();
Just leaving this as a breadcrumb in case someone else does something similar.

ng-click not working on submit button

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.

Resources