ng-submit won't call function inside directive controller - javascript

ok, i think the question says it all, but just to be clear, i have the following form (I know it's long... I'm using bootstrap... and jquery):
<form class="form-horizontal" role="form" ng-submit="cal.addEvent()"novalidate>
<div class="form-group">
<label class="control-label col-sm-2" for="title">Title:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="title" placeholder="Event Title" ng-model="cal.newEvent.title">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="desc">Description:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="desc" placeholder="Event Description" ng-model="cal.newEvent.description">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="stime">Start Time:</label>
<div class="col-sm-8">
<input type="time" class="form-control" id="stime" ng-model="cal.newEvent.start">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="etime">End Time:</label>
<div class="col-sm-8">
<input type="time" class="form-control" id="etime" ng-model="cal.newEvent.end">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="submit" class="btn btn-success btn-block" data-role="none">Add Event</button>
</div>
</div>
</form>
this form is inside a directive which looks like this:
app.directive("calendar", function($http) {
return {
restrict: "E",
templateUrl: "templates/calendar.html",
scope: true,
transclude:true,
link: function(scope) {
//there's a bunch of code here that I don't believe has anything to do with ng-submit so i left it out
},
controller: ["$scope", "$rootScope", function($scope, $rootScope){
this.newEvent = {};
this.removeEvent = function(index){
$http.post("classes/main.php", {"fn": "calendarDel", "id": $scope.chosen[index].id}).success(function(data){
$scope.getEvents($scope.chosen[index].date);
});
}
this.addEvent = function(){
//this.newEvent.date = $scope.dateString;
console.log("AddEvent");
console.log(this.newEvent);
}
$scope.getEvents = function(date){
$http.post("classes/main.php", {"fn": "calendar", "id": $rootScope.user.id, "data": date}).success(function(data){
if(!data.Error){
$scope.chosen = data;
}
});
}
}],
controllerAs: 'cal'
};
});
the problem is that when i try to submit my form, i see no indication that the function has been called... i expect to at least see console.log("AddEvent");
does anybody see what may be causing this problem here?
FYI
the form is in a bootstrap 3 modal div, which is inside the same directive it's called from --- if you need to see the "bigger picture", so to speak, just ask :)
i have tried this.addEvent(), $scope.addEvent(), $rootScope.addEvent() no change

You should just be calling addEvent()
<form class="form-horizontal" role="form" ng-submit="addEvent()" novalidate>
and bind the function to your scope like
$scope.addEvent = function() {
From the angular docs on expresssions
expressions are evaluated against a scope object
so you should not write the expression as ng-submit="$scope.addEvent()" etc

You should add bindToController: true to the directive and specify scope: {} to create an isolate scope.
When an isolate scope is used for a component (see above), and controllerAs is used, bindToController: true will allow a component to have its properties bound to the controller, rather than to scope. When the controller is instantiated, the initial values of the isolate scope bindings are already available.
Reference: $compile

Related

AngularJS 1.6.8: Unable to submit form and display success message

I have a simple query submission form with name, email and query fields and a component with a controller function having the submit function to submit the form.
I am using ng-submit directive in the <form></form> tag to submit the user input and display a success message on submission.
below is the code for the respective files.
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div>
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService,$rootScope) {
var vm = this;
$scope.navigate = function(home){
$state.go(home)
};
$scope.saveform = function(){
$scope.name= vm.name;
$scope.email= vm.email;
$scope.query= vm.email;
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted."
};
$scope.user = userService;
};
//localStorage code
function userService($rootScope) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
UPDATE: On Submit, When I check the response in network tab in dev tools, I do not see the submitted values. All I see is the markup.
In your template, the name of the method is saveform:
ng-submit="saveform()"
But in your controller, it's save:
$scope.save = function() { ... }
Rename it to saveform:
$scope.saveform = function() { ... }

How do I trigger all validations when submit button is clicked?

I've added validations for my form and I wanted it to trigger each and every validation when submit button is clicked. I tried googling for how to trigger them but it seems they are not working for me.
Here's my code for the form
<form id="CustomerForm" class="form-horizontal group-border stripped" name="CustomerDetails" novalidate ng-submit="CustomerDetails.$valid && AddCustomer()">
<div class="form-group" ng-class="{'has-error': CustomerDetails.cname.$invalid && !CustomerDetails.cname.$pristine}">
<label class="col-lg-2 col-md-3 control-label">Customer Name</label>
<div class="col-lg-10 col-md-9">
<input type="text" ng-model="CusDetails.cname" class="form-control" name="cname" id="cname" required />
<p ng-show="CustomerDetails.cname.$error.required && !CustomerDetails.cname.$pristine" class="help-block">Customer name required!</p>
</div>
</div>
<!--end of .form-group-->
<div class="form-group" ng-class="{'has-error': CustomerDetails.comname.$invalid && !CustomerDetails.comname.$pristine}">
<label class="col-lg-2 col-md-3 control-label">Company Name</label>
<div class="col-lg-10 col-md-9">
<input type="text" ng-model="CusDetails.comname" class="form-control" name="comname"id="comname" required />
<p ng-show="CustomerDetails.comname.$error.required && !CustomerDetails.comname.$pristine" class="help-block">Comapany name required!</p>
</div>
</div>
<!--end of .form-group-->
<div class="form-group" ng-class="{'has-error': CustomerDetails.ctel.$invalid && !CustomerDetails.ctel.$pristine}">
<label class="col-lg-2 col-md-3 control-label" for="">Telephone Number</label>
<div class="col-lg-10 col-md-9">
<div class="input-group input-icon">
<span class="input-group-addon"><i class="fa fa-phone s16"></i></span>
<input ng-model="CusDetails.tel" class="form-control" name="ctel" type="text" placeholder="(999) 999-9999" id="ctel" required >
<p ng-show="CustomerDetails.ctel.$error.required && !CustomerDetails.ctel.$pristine" class="help-block">Telephone number required!</p>
</div>
</div>
</div>
<!-- End .form-group -->
<div class="form-group" ng-class="{'has-error': CustomerDetails.email.$invalid && !CustomerDetails.email.$pristine}">
<label class="col-lg-2 col-md-3 control-label" for="">Email address</label>
<div class="col-lg-10 col-md-9">
<input ng-model="CusDetails.email" type="email" class="form-control" name="email" placeholder="someone#example.com" id="email" required >
<p ng-show="CustomerDetails.email.$error.required && !CustomerDetails.email.$pristine" class="help-block">Email is required!</p>
<p ng-show="CustomerDetails.email.$error.email && !CustomerDetails.email.$pristine" class="help-block">Please Enter valid email address.</p>
</div>
</div>
<!-- End .form-group -->
<div class="form-group">
<div class="col-lg-9 col-sm-9 col-xs-12">
<button name="btnSubmit" type="submit" class="btn btn-info pad"><span class="fa fa-user-plus"></span> Add Customer</button>
<button type="button" id="cancel" class="btn btn-default pad">Cancel</button>
</div>
</div>
</form>
UPDATE: I have change the code according to Adrian Brand but still no trigger. What am I doing wrong?
Here's my angularjs for the form. (controller)
(function () {
'use strict';
angular
.module('efutures.hr.controllers.customer', [])
.controller('AddCustomerController', AddCustomerController);
AddCustomerController.$inject = ['$scope', '$location', '$rootScope', '$http', 'CustService'];
function AddCustomerController($scope, $location, $rootScope, $http, CustService) {
(function initController() {
})();
$scope.AddCustomer = function () {
var CustomerDetails = {
cname: $scope.CusDetails.cname,
comname: $scope.CusDetails.comname,
tel: $scope.CusDetails.tel,
email: $scope.CusDetails.email
};
if ($scope.CustomerDetails.$valid) {
CustService.Customer(CustomerDetails, function (res) {
console.log(res);
$.extend($.gritter.options, {
position: 'bottom-right',
});
if (res.data == 'success') {
$.gritter.add({
title: 'Success!',
text: 'Successfully added the new customer ' + '<h4><span class="label label-primary">' + CustomerDetails.cname + '</span></h4>',
time: '',
close_icon: 'l-arrows-remove s16',
icon: 'glyphicon glyphicon-ok-circle',
class_name: 'success-notice'
});
$scope.CusDetails = {};
$scope.CustomerDetails.$setPristine();
}
else {
$.gritter.add({
title: 'Failed!',
text: 'Failed to add a new customer. Please retry.',
time: '',
close_icon: 'l-arrows-remove s16',
icon: 'glyphicon glyphicon-remove-circle',
class_name: 'error-notice'
});
}
});
}
}
}
})();
I even tried making the form submitted true, still didn't work.
The only thing that worked for me is the disabling the button until its validated but that isn't the requirement. I want it to trigger when the submit form is clicked. Help would be greatly appreciated.
In the click event where you wanted to trigger the validation, add the following:
vm.triggerSubmit = function() {
vm.homeForm.$setSubmitted();
...
}
This works for me. To know more about this click here : https://code.angularjs.org/1.3.20/docs/api/ng/type/form.FormController
Your problem lies in the fact that your submit button is not contained in the form so the form never gets submitted. You are just running the controller method via a click handler.
Form validation is not a controller concern and has no place in the controller. It is purely a view concern.
In your form you put a ng-submit="CustomerDetails.$valid && AddCustomer()" and take the click handler off the submit button and place the button row within the form. This way the view will only submit if the form is valid. Do not pollute your controllers with form validation and keep it all contained in your view. You should look into the controller as syntax and then you will not even have access to the $scope in your controllers.

Call a function from a directive to the controller

I am trying to implement a simple comment writing from client to server using angular.
Here is the HTML for the comment form:
<form id="commentsForm" name="commentsForm" ng-submit="submitComment()">
<fieldset>
<legend>Post a comment</legend>
<div class="form-group comment-group">
<label for="comment" class="control-label">Comment</label>
<div class="control-field">
<textarea class="form-control" cols="30" rows="5" name="comment" id="comment-textarea" tabindex="3" ng-model="c.comment" required></textarea>
</div>
</div>
<div class="form-group button-group">
<div class="control-field">
<button type="submit" class="btn btn-primary btn-comment" tabindex="4" >Post comment</button>
</div>
</div>
</fieldset>
</form>
And the controller I use with the "submitComment()" function:
'use strict';
// inject scope, services (CommentService)
//
angular.module('mean.groups').controller('CommentsCtrl', ['$scope','Global', 'CommentsService', function($scope, CommentsService) {
$scope.c = {};
console.log("controller is online");
$scope.submitComment = function (comment) {
console.log("activted submit comment function");
var postCommentData = {};
postCommentData.postingTime = new Date();
postCommentData.commentData = $scope.c.comment;
console.log("in controller:" + postCommentData);
CommentsService.postComment(postCommentData)
.then(function () {
$scope.commentsForm.$setPristine();
$scope.c = {};
console.log('posted');
});
};
}]);
And the directive I use wrap the html:
'use strict';
angular.module('mean.directives').directive('commentForm', function() {
return {
restrict: 'E',
templateUrl: 'comments/views/comment-form.html',
controller: 'CommentsCtrl',
controllerAs: 'commentsForm'
}
});
The service I use is a standard http.post service but I don't understand why the console.log() in the controller function is not triggered with the comment.
Thanks.
You aren't using the controller, to use the controller add the controllerAs object before the functions.
<form id="commentsForm" name="commentsForm" ng-submit="commentsForm.submitComment()">
<fieldset>
<legend>Post a comment</legend>
<div class="form-group comment-group">
<label for="comment" class="control-label">Comment</label>
<div class="control-field">
<textarea class="form-control" cols="30" rows="5" name="comment" id="comment-textarea" tabindex="3" ng-model="commentsForm.c.comment" required></textarea>
</div>
</div>
<div class="form-group button-group">
<div class="control-field">
<button type="submit" class="btn btn-primary btn-comment" tabindex="4" >Post comment</button>
</div>
</div>
Here is the answer, I just add :
link: function($scope, element, attrs) {
$scope.submitComment = function () {
//my code logic ...
}
}
And changed the replace to false:
replace: false;

Controller on Modal not working on AngularJS

I have a main users page with users, if you select a user, a modal is opened and should show the user information.
The problem is that the $scope doesn't seem to be working, as it doesn't show the user data on the modal. But if I show that user data anywhere on the main users page, it works fine.
I have this controller:
function userController($scope, $modal, $http, $rootScope) {
var usrCtrl = this;
$scope.users = null;
$scope.openUserForm = function () {
var modalInstance = $modal.open({
templateUrl: 'views/modal_user_form.html',
controller: userController,
windowClass: "animated flipInY"
});
};
var session = JSON.parse(localStorage.session);
$http({
method: 'GET',
url: $rootScope.apiURL+'getAllClientUsers/'+session,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response){
if(response.ErrorMessage === null && response.Result !== null){
$scope.users = response.Result;
}
});
//**This is the code that opens the modal
$scope.editViewUser = function(user){
for (var key in $scope.users) {
if($scope.users[key].SecUserId === user){
$scope.selectedUser = $scope.users[key];
}
}
$scope.openUserForm();
};
};
And this modal:
<div ng-controller="userController">
<div class="inmodal">
<div class="modal-header">
<h4 class="modal-title">Create or Edit User</h4>
<small class="font-bold">Use this modal to create or edit a user</small>
</div>
<div class="modal-body">
<form method="get" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label">Nombre</label>
<div class="col-sm-10"><input ng-model="selectedUser.FirstName" type="text" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Apellido</label>
<div class="col-sm-10"><input ng-model="selectedUser.LastName" type="text" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Usuario</label>
<div class="col-sm-10"><input ng-model="selectedUser.UserName" type="text" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Email</label>
<div class="col-sm-10"><input ng-model="selectedUser.Email" type="email" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Activo</label>
<div class="col-sm-10">
<div><label> <input ng-model="selectedUser.FirstName" type="checkbox" value=""></label></div>
</div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Email Verificado</label>
<div class="col-sm-10">
<div><label> <input ng-model="selectedUser.FirstName" type="checkbox" value=""></label></div>
</div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Privilegios</label>
<div class="col-sm-10">
<select class="form-control m-b" name="account">
<option ng-repeat="priv in selectedUser.EffectivePrivileges">{{ priv }}</option>
</select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" ng-click="cancel()">Close</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Save changes</button>
</div>
</div>
</div>
I tried injecting the controller and also using the ng-controller, and scope property for modal.
What am I missing?
The problem is that modal template is compiled in the scope which doesn't inherit from your $scope. To make a connection between them you can tell modal to create a new child scope of your scope:
$scope.openUserForm = function () {
var modalInstance = $modal.open({
scope: $scope, // <----- add this instruction
templateUrl: 'views/modal_user_form.html',
controller: userController,
windowClass: "animated flipInY"
});
};
Generally, the modal would have its own controller rather than point to the controller that its called from. You would inject the model (selectedUser) into the modal controller, work on it, then pass it back to parent. Also, you can give user option to cancel in which case no changes are made to parent controller model.
Modal controller:
app.controller('UserModalController', [
'$scope',
'$modalInstance',
'selectedUser',
function ($scope, $modalInstance, selectedUser) {
$scope.selectedUser = selectedUser;
$scope.cancel= function () {
// user cancelled, return to parent controller
$modalInstance.dismiss('cancel');
};
$scope.save = function () {
// close modal, return model to parent controller
$modalInstance.close($scope.selectedUser);
};
]);
Changes to main controller:
var modalInstance = $modal.open({
templateUrl: 'views/modal_user_form.html',
controller: 'UserModalController',
windowClass: "animated flipInY",
resolve: {
selectedUser: function() {
return $scope.selectedUser;
}
}
});
modalInstance.result.then(function(updatedUser) {
// deal with updated user
}, function() {
// modal cancelled
});

re enabling ng-disabled button in Angular JS

I am a newbie to AngularJS. I have created a form with fields which is disabled using ng-disabled by default. when I click on the edit <button> I want these fields to re-enable.
HTML
<form class="form-horizontal" role="form" ng-submit="edit_setting()" ng-controller="ExchangeController">
<div class="form-group">
<label>Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.name" ng-disabled="true">
</div>
</div>
<div class="form-group">
<label>Host Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.host_name" required ng-disabled="true">
</div>
</div>
<div class="form-group">
<label>Address</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.address" ng-disabled="true">
</div>
</div>
</form>
Controller
function ExchangeController($scope, $http, $cookieStore, $location) {
var edit_exchange_setting = "https://pvbp.com/api/settings.html?contactid=292351&exchange_id=7124&clearinghouseid=1&token=e5349652507c0esae86d50fdbdc53222cf97&page=view";
$http.get(edit_exchange_setting).success(function(response){
$scope.exchange_dt.exchange_name = response.name;
$scope.exchange_dt.exchange_host_name = response.host_name;
$scope.exchange_dt.exchange_last_processed_date = response.address;
});
$scope.edit_exchange_setting_click = (function(){
// how can i make the fields re enable here
});
}
in controller create scope variable,
$scope.disabled= true;
and replace all ng-disabled with that variable like,
...ng-model="exchange_dt.name" ng-disabled="disabled"....
when you click on edit button set $scope.disabled to false like,
$scope.edit_exchange_setting_click = (function(){
$scope.disabled = false;
});
you can have a scope variable keeping the true or false value.and a setter for that variable.
function ExchangeController($scope, $http, $cookieStore, $location) {
var edit_exchange_setting = "https://pvbp.com/api/settings.html?contactid=292351&exchange_id=7124&clearinghouseid=1&token=e5349652507c0esae86d50fdbdc53222cf97&page=view";
$http.get(edit_exchange_setting).success(function(response){
$scope.exchange_dt.exchange_name = response.name;
$scope.exchange_dt.exchange_host_name = response.host_name;
$scope.exchange_dt.exchange_last_processed_date = response.address;
});
$scope.edit_exchange_setting_click = (function(){
// how can i make the fields re enable here
});
$scope.dtName=true;
$scope.isdtNameDisabled=function()
{
return $scope.dtName;
};
$scope.updatedtName=function(flag)
{
$scope.dtName=flag;
};
}
and in your HTML you can bind that getter function.
<div class="form-group">
<label>Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.name" ng-disabled="isdtNameDisabled()>
</div>
</div>
You need to create a variable at the top of controller say
$scope.mydisabled=true;
then set your ng-disable with the variable
ng-disabled="mydisabled"
and on click of edit button set its value to false
$scope.mydisabled=false;
UPDATE
Fiddle
A different (however similar) approach is to wrap your form contents in a fieldset and have ng-disabled in the fieldset only rather than in all the input fields. To make the html more cleaner.
<form class="form-horizontal" role="form" ng-submit="edit_setting()" ng-controller="ExchangeController">
<fieldset ng-disabled ="isFormSetForSaving">
<div class="form-group">
<label>Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.name">
</div>
</div>
<div class="form-group">
<label>Host Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.host_name" required>
</div>
</div>
<div class="form-group">
<label>Address</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.address">
</div>
</div>
</fieldset>
</form>
and now in the controller set the isFormSetForSaving to true/false as per your logic.
function ExchangeController($scope, $http, $cookieStore, $location) {
$scope.isFormSetForSaving = true;
var edit_exchange_setting = "https://pvbp.com/api/settings.html?contactid=292351&exchange_id=7124&clearinghouseid=1&token=e5349652507c0esae86d50fdbdc53222cf97&page=view";
$http.get(edit_exchange_setting).success(function(response){
$scope.exchange_dt.exchange_name = response.name;
$scope.exchange_dt.exchange_host_name = response.host_name;
$scope.exchange_dt.exchange_last_processed_date = response.address;
});
$scope.edit_exchange_setting_click = (function(){
// how can i make the fields re enable here
$scope.isFormSetForSaving = false;
});
}

Categories