I am trying to send form data from a contact form to a web service by concat string method. I have made a controller who looks like this:
// contact controller
eventApp.controller('contactController', ['$scope', '$http', function($scope, $http) {
$scope.obj = {
val1: 'personName',
val2: 'email',
val3: 'subject',
val4: 'emailMessage'
};
$scope.sendMessage = function(obj) {
var string = '#/path/' + $scope[obj.val1] + '/' + $scope[obj.val2] + '/' + $scope[obj.val3] + '/' + $scope[obj.val4];
//$scope.debug.val = string;
console.log(obj);
};
}]);
How do I make it possible to fill in input values for the values 'personName', 'email', 'subject' and 'emailMessage' like 'John', 'john#email.com', 'webservice' and 'Hello!'? Should I use expressions?
In the DOM console I get an object answer like this when I tap the send button:
Object {val1: "personName", val2: "email", val3: "subject", val4: "emailMessage"}
My HTML is looking like this:
<!-- partial-contact.html -->
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div id="form-container">
<!-- Contact Heading -->
<div class="page-header text-center">
<h1><i class="fa fa-comment"></i> Kontakt</h1>
<p>Ved spørsmål skriv ein epost i kontaktskjemaet under.</p>
</div>
<!-- Form -->
<!-- use ng-submit to catch the form submission and use our Angular function -->
<form id="contactForm" name="contactForm" novalidate ng-submit="contactForm()" ng-controller="contactController" method="post">
<!-- Name -->
<div class="input-group margin-bottom-sm">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input id="personName" class="form-control" type="text" name="personName" ng-model="contactData.personName" placeholder="Namn *" required />
</div>
<!-- Email -->
<div class="input-group margin-bottom-sm">
<span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
<input id="email" class="form-control" type="email" name="email" ng-model="contactData.email" placeholder="Epost *" required />
</div>
<!-- Subject -->
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-info"></i></span>
<input id="subject" class="form-control" type="text" name="subject" ng-model="contactData.subject" placeholder="Emne *" required />
</div>
<!-- Email Message & Button -->
<div class="input-group">
<div class="input-group-btn">
<!-- Email Message -->
<textarea id="emailMessage" type="text" class="form-control" name="emailMessage" ng-model="contactData.emailMessage" ng-minlength=10 ng-maxlength=300 placeholder="Melding..." required></textarea>
<!-- Button -->
<button id="submit" type="submit" class="btn btn-primary" ng-click="sendMessage(obj)"><i class="fa fa-angle-double-right"></i></button>
</div>
</div>
<br>
</form>
</div>
</div>
</div>
contactData is your object in the controller scope holding the data.
use $scope.contactData[obj.val1] instead of $scope[obj.val1]
Related
I have a dependent drop down for country and state selection. State drop down is dependent on country selection. Actually i create a directive for it in a seprate file module. Below is this. So when i am going on edit page to edit this then no state display selected.
Basically i just wanted to pass selected country from controller to directive. If i get this then i simply load the corresponding state value from directive. Please help any one. What is the solution of it???
Thanks in advance:)
My Directive is this :
function(window) {
"use strict";
var template = '<div class="control-group">'
template += '<label for="country" class="control-label">{{countryLabel}}</label>';
template += '<div class="controls" val="{{ngModel.country}}">';
template += '<select name="country" ng-change="selectCountry()" ng-model="ngModel.country" required class="form-control">';
template += '<option value="">Select Country</option>';
template +='<option ng-repeat="theCountry in countries track by $index" >{{theCountry}}</option>';
template +='</select>';
template +='</div>';
template +='</div>';
template += '<div class="control-group">';
template += '<label for="country" class="control-label">{{stateLabel}}</label>';
template += '<div class="controls">';
template += '<select name="state" ng-model="ngModel.county" ng-disabled="!ngModel.country" required class="form-control">';
template += '<option value="">Select State</option>';
template +='<option ng-repeat="optStates in states track by $index">{{optStates}}</option>';
template +='</select>';
template +='</div>';
template +='</div>';
angular
.module("angularCountryState")
.directive("countryStateSelect", [ function () {
return {
restrict: "E",
template: template,
scope: { country: "=", countryState: "=?state", ngModel: '='},
link: function (scope, element, attrs) {
scope.countryLabel = "Country";
scope.stateLabel = "State";
if(typeof attrs.countryLabel != 'undefined'){
scope.countryLabel = attrs.countryLabel;
}
if(typeof attrs.stateLabel != 'undefined'){
scope.stateLabel = attrs.stateLabel;
}
alert(scope.country);
scope.countries = new Array("Afghanistan", "Albania", "Algeria", "American Samoa", "Angola", "Anguilla");
scope.state = new Array();
scope.state[1]="Badakhshan|Badghis|Baghlan|Balkh|Bamian|Farah|Faryab|Ghazni|Ghowr|Helmand|Herat|Jowzjan|Kabol|Kandahar|Kapisa|Konar|Kondoz|Laghman|Lowgar|Nangarhar|Nimruz|Oruzgan|Paktia|Paktika|Parvan|Samangan|Sar-e Pol|Takhar|Vardak|Zabol";
scope.state[2]="Berat|Bulqize|Delvine|Devoll (Bilisht)|Diber (Peshkopi)|Durres|Elbasan|Fier|Gjirokaster|Gramsh|Has (Krume)|Kavaje|Kolonje (Erseke)|Korce|Kruje|Kucove|Kukes|Kurbin|Lezhe|Librazhd|Lushnje|Malesi e Madhe (Koplik)|Mallakaster (Ballsh)|Mat (Burrel)|Mirdite (Rreshen)|Peqin|Permet|Pogradec|Puke|Sarande|Shkoder|Skrapar (Corovode)|Tepelene|Tirane (Tirana)|Tirane (Tirana)|Tropoje (Bajram Curri)|Vlore";
scope.state[3]="Adrar|Ain Defla|Ain Temouchent|Alger|Annaba|Batna|Bechar|Bejaia|Biskra|Blida|Bordj Bou Arreridj|Bouira|Boumerdes|Chlef|Constantine|Djelfa|El Bayadh|El Oued|El Tarf|Ghardaia|Guelma|Illizi|Jijel|Khenchela|Laghouat|M'Sila|Mascara|Medea|Mila|Mostaganem|Naama|Oran|Ouargla|Oum el Bouaghi|Relizane|Saida|Setif|Sidi Bel Abbes|Skikda|Souk Ahras|Tamanghasset|Tebessa|Tiaret|Tindouf|Tipaza|Tissemsilt|Tizi Ouzou|Tlemcen";
scope.state[4]="Eastern|Manu'a|Rose Island|Swains Island|Western";
scope.state[5]="Andorra la Vella|Bengo|Benguela|Bie|Cabinda|Canillo|Cuando Cubango|Cuanza Norte|Cuanza Sul|Cunene|Encamp|Escaldes-Engordany|Huambo|Huila|La Massana|Luanda|Lunda Norte|Lunda Sul|Malanje|Moxico|Namibe|Ordino|Sant Julia de Loria|Uige|Zaire";
scope.selectCountry = function(){
var selectedCountry = scope.ngModel.country;
var indexCountry = scope.countries.indexOf(selectedCountry)+1;
scope.states = scope.state[indexCountry].split("|");
scope.countryState = '';
if(scope.states.length == 1){
scope.states = new Array(selectedCountry);
}
//indexCountry correspond to the "Select" label
if(indexCountry == 0){
scope.states = new Array("");
}
}
// scope.selectCountry();
}
};
}]);
}());
My Controller Is This
app.controller('EmployeeloanCtrl', function ($scope, $rootScope, $routeParams, Restangular, showAlertSrvc, ngTableParams, $filter, listService, $location, $cookieStore){
//This Function Is Use To Get The Detail Of The User Also Update The Detail.
$scope.getUserDetail = function(){
Restangular.one('users', uid).get({is_archived:'0'}).then(function(user){
$scope.country = "india";
$scope.user = user;
//This Function Is Use To Update The User Personal Details.
$scope.editUserinfo = function(user){
Restangular.one('users', uid).customPUT(user).then(function(responce){
$location.path('/employee/loan/addloaninfo');
});
};
});
};
});
This is my html code :
<form ng-submit="editAccount(user)" class="form-horizontal">
<fieldset>
<div class="control-group">
<label for="password" class="control-label">Password</label>
<div class="controls">
<span ng-controller="modalpchangeCtrl as ctrl">
<a class="btn btn-small btn-success" ng-click="ctrl.showModal(notification._id,'sender_id')">Change Password</a>
</span>
</div> <!-- /controls -->
</div> <!-- /control-group -->
<div class="control-group">
<label for="first name" class="control-label">First Name</label>
<div class="controls">
<input type="text" class="span4" placeholder="First Name" ng-model="user.first_name" ng-required="true">
</div> <!-- /controls -->
</div> <!-- /control-group -->
<div class="control-group">
<label for="middle name" class="control-label">Middle Name</label>
<div class="controls">
<input type="text" class="span4" placeholder="Middle Name" ng-model="user.middle_name" ng-required="true">
</div> <!-- /controls -->
</div> <!-- /control-group -->
<div class="control-group">
<label for="last name" class="control-label">Last Name</label>
<div class="controls">
<input type="text" class="span4" placeholder="Last Name" ng-model="user.last_name" ng-required="true">
</div> <!-- /controls -->
</div> <!-- /control-group -->
<div class="control-group">
<label for="email" class="control-label">Email</label>
<div class="controls">
<input type="text" class="span4" ng-readonly="true" placeholder="Email" ng-model="user.email" ng-required="true">
</div> <!-- /controls -->
</div> <!-- /control-group -->
<div class="control-group">
<label for="phone" class="control-label">Address line 1</label>
<div class="controls">
<input type="text" class="span4" placeholder="address line 1" ng-model="user.address_line_1" ng-required="true">
</div> <!-- /controls -->
</div> <!-- /control-group -->
<div class="control-group">
<label for="phone" class="control-label">Address line 2</label>
<div class="controls">
<input type="text" class="span4" placeholder="address line 2" ng-model="user.address_line_2" ng-required="true">
</div> <!-- /controls -->
</div> <!-- /control-group -->
<country-state-select ng-model="user"></country-state-select>
<div class="control-group">
<label for="city" class="control-label">City</label>
<div class="controls">
<input type="text" class="span4" placeholder="city" ng-model="user.city">
</div> <!-- /control-group -->
</div>
<div class="control-group">
<label for="post_code" class="control-label">Post code</label>
<div class="controls">
<input type="text" class="span4" placeholder="post code" ng-model="user.post_code" ng-required="true">
</div> <!-- /controls -->
</div> <!-- /control-group -->
<div class="control-group">
<div class="form-actions">
<button class="btn btn-primary" type="submit">Save</button>
<a class="btn" href="/#/">Cancel</a>
</div> <!-- /form-actions -->
</fieldset>
</form>
Suggetion i tried :
I also look a plunker link http://plnkr.co/edit/gp0zIwnj9Oz3IpQPXhDI?p=preview .
I just want the data which i set from controller i wanted to get this in alert.
I have a profile with a series of cards. Each card has a type (e.g. gallery card, quote card, etc) and the profile can have 1 or more of each type. I'm building a profile editor and want to be able to open an edit form in a modal. Each card has its own type of form with unique inputs, but there is only one form per card type, since we can't know in advance how many cards of each type a profile will have.
For each form, I have a number of ng-init directives to prepopulate the edit form with the current model's attributes. This works great except that if I have more than one card of a type, each card's edit form will have the data from the last card in the set. Is there a way I can trigger the ng-init directives to run again when I open the form (e.g. with an ng-click) so that the user will always see the current model's attributes?
Here is what one of my card forms looks like:
<% if c.class.name == 'QuoteCard' %>
<div class="row-scrollable" ng-show="view === 'quote-card'">
<div class="col-lg-12">
<form accept-charset="UTF-8" name="editQuoteCardForm" ng-submit="update({card: editQuoteCard, type: 'quote_card'})" novalidate>
<input name="utf8" type="hidden" value="✓">
<input name="authenticity_token" type="hidden" ng-model="editQuoteCard.token" ng-init="editQuoteCard.token='<%= form_authenticity_token %>'">
<input name="id" type="hidden" ng-model="editQuoteCard.id" ng-init="editQuoteCard.id='<%= c.id %>'">
<div class="form-group">
<label>Title</label>
<br style="clear:both;" />
<input type="text" class="form-control" name="title" ng-init='editQuoteCard.title = "<%= c.title %>"' ng-model="editQuoteCard.title" required>
</div>
<div class="form-group">
<label>Attribution</label>
<br style="clear:both;" />
<input type="text" class="form-control" name="attribution" ng-init='editQuoteCard.title = "<%= c.attribution %>"' ng-model="editQuoteCard.attribution">
</div>
<div class="form-group">
<label>Quote</label>
<br style="clear:both;" />
<textarea rows="3" class="form-control" name="quote" ng-init='editQuoteCard.title = "<%= c.quote %>"' ng-model="editQuoteCard.quote" required></textarea>
</div>
<div class="form-group">
<label>Media</label>
<br style="clear:both;" />
<input type="hidden" class="form-control" name="photo" ng-model="editQuoteCard.image">
<input type="hidden" class="form-control" name="video" ng-model="editQuoteCard.video">
<%= photo = Photo.find_by(quote_card_id: c.id) %>
<%= video = Video.find_by(quote_card_id: c.id) %>
<div class="profile-builder attachment"
ng-init='<%= "editQuoteCard.image = #{{ image_url: photo.image.url, id: photo.id }.to_json}" unless photo.nil? %>'
ng-init='<%= "editQuoteCard.video = #{{ media_url: video.media_url, media_type: video.media_type, id: video.id }.to_json}" unless video.nil? %>'>
<div ng-show="editQuoteCard.video" class="content video-content result iframe">
<div class="caption delete-btn" ng-click="editQuoteCard.video = undefined;">
<i class="fa fa-times"></i>
</div>
<iframe ng-if="editQuoteCard.video.media_type === 'Youtube'" ng-src="{{editQuoteCard.video.media_url + '?showinfo=0&autohide=1' | trustAsResourceUrl}}" frameborder="0" id="ytplayer" type="text/html"></iframe>
<iframe ng-if="editQuoteCard.video.media_type === 'Vimeo'" ng-src="{{editQuoteCard.video.media_url + '?badge=0&byline=0&title=0' | trustAsResourceUrl}}" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
<div ng-show="editQuoteCard.image" class="content result">
<div class="delete-btn" ng-click="editQuoteCard.image = undefined;">
<i class="fa fa-times"></i>
</div>
<div class="image-container" ng-style="{'background-image': 'url(' + editQuoteCard.image.image_url + ')'}"></div>
</div>
</div>
</div>
<br style="clear:both;" />
<div class="form-group">
<input class="btn btn-primary" style="float:right;" name="commit" type="submit" value="Update Card" ng-disabled="editQuoteCardForm.$invalid">
<div class="btn btn-default" style="float:right;margin-right:10px;" ng-click="openMediaBrowser({type: '<%= c.class %>', id: <%= c.id %>, index: <%= i %>});" ng-show="!editQuoteCard.image && !editQuoteCard.video">Add Media</div>
</div>
</form>
</div>
</div>
<% end %>
And in my controller, I have an edit function that opens the modal with the correct form:
$scope.edit = function(options) {
modal.open({
content: $('#edit_card_' + options.index + '_form'),
elem: $('#edit_card_' + options.index + '_form_container')
})
};
I am unable to get automatic radio button checked when I edit the User From using following Html and AngularJs Code. When I console {{changeUser}} this returns following data
{"id":1,"username":"Ramesh","password":"Ramesh1#23","role":"admin","active":"no"}. When I load the edit form I have to automatically checked the no radio button in the following code.
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form class="form-horizontal form-bordered" name="editUserForm" data-ng-submit="userEdit(changeUser)">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Username*</label>
<div class="col-md-4">
<input class="form-control" type="text" name="userName" data-ng-model="changeUser.username" value="{{ changeUser.username }}" data-ng-pattern="/^[a-z0-9_ .-]{5,15}$/i" required />
<span style="color:red" class="error" data-ng-show="editUserForm.userName.$error.pattern" >Only letters, integers, and underscores.Minimum 5 characters to maximum 15 characters.</span>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Password*</label>
<div class="col-md-4">
<input class="form-control" type="password" name="changePassword" data-ng-model="changeUser.password" value="{{ changeUser.password}}" data-ng-pattern="usersPattern.password" required />
<span style="color:red" class="error" data-ng-show="editUserForm.changePassword.$error.pattern">Minimum of 8 characters, 1 capital letter,1 lowercase, 1 special-case and 1 numeric.</span>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Action</label>
<div class="col-md-4">
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="optionsRadios2" data-ng-model="changeUser.active" value="yes"/>
Yes
</label>
<label class="radio-inline">
<input type="radio" name="optionsRadios2" data-ng-model="changerUser.active" value="no"/>
No
</label>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn purple" data-ng-disabled= "editUserForm.$invalid">
<i class="fa fa-check"></i> Edit</button>
<button type="button" class="btn red" data-ng-click="cancelEdit()">Cancel</button>
</div>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
The Controller is
(function (){
"use strict";
function UsersEditController($scope, UserFactory, $http, $location) {
$scope.$on('$viewContentLoaded', function () {
App.initAjax(); // initialize core components
});
$scope.changeUser = {};
$scope.changeUser = UserFactory.get();
$scope.userEdit = function(data) {
$scope.changeUser = data;
console.log($scope.changeUser);
};
$scope.usersPattern = {
password: '((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%]).{8,20})'
};
$scope.cancelEdit = function() {
$location.path('users');
};
}
UsersEditController.$inject = ['$scope', 'UserFactory', '$http', '$location'];
angular.module('books').controller('UsersEditController', UsersEditController);
})()
And I guess this is your answer (even without js code provided :) )
https://stackoverflow.com/a/18446612/552194
You need to add ng-value and use it instead of the standard value
I'm running into some problems with Angular 1.3.2
I'm expecting to see the formData object being populated with whatever is being typed in the input fields
I have the following code.
angular.module('formApp', [])
.controller('FormController', function ($scope, $http) {
$scope.formData = {};
$scope.processForm = function () {
};
});
<div class="form-container" ng-app="formApp" ng-controller="FormController">
<div class="container">
<form>
<div id="name-group" class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" placeholder="Bruce Wayne" ng-model="formData.name">
<span class="help-block"></span>
</div>
<div id="superhero-group" class="form-group">
<label>Superhero Alias</label>
<input type="text" name="superheroAlias" class="form-control" placeholder="Caped Crusader"
ng-model="formData.superheroAlias">
<span class="help-block"></span>
</div>
<button type="submit" class="btn btn-success btn-lg btn-block">
<span class="glyphicon glyphicon-flash"></span> Submit!
</button>
</form>
<pre>
{{ formData }}
</pre>
</div>
</div>
you have a typo in your ngcontroller syntax. it should be ng-controller
<div class="form-container" ng-app="formApp" ng-controller="FormController">
Copied your code and it is working, see below:
angular.module('formApp', [])
.controller('FormController', function ($scope, $http) {
$scope.formData = {};
$scope.processForm = function () {
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="form-container" ng-app="formApp" ng-controller="FormController">
<div class="container">
<form>
<div id="name-group" class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" placeholder="Bruce Wayne" ng-model="formData.name">
<span class="help-block"></span>
</div>
<div id="superhero-group" class="form-group">
<label>Superhero Alias</label>
<input type="text" name="superheroAlias" class="form-control" placeholder="Caped Crusader"
ng-model="formData.superheroAlias">
<span class="help-block"></span>
</div>
<button type="submit" class="btn btn-success btn-lg btn-block">
<span class="glyphicon glyphicon-flash"></span> Submit!
</button>
</form>
<pre>
{{ formData }}
</pre>
</div>
</div>
I have a problem with a button who gave me an error message in the DOM console. The error message is:
TypeError: object is not a function
at angular.js:10822
at angular.js:19062
at k.$eval (angular.js:12658)
at k.$apply (angular.js:12756)
at HTMLFormElement. (angular.js:19061)
at angular.js:2843
at r (angular.js:325)
at HTMLFormElement.c (angular.js:2842)
I am using AngularJS and here is my HTML code:
<!-- partial-contact.html -->
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div id="form-container">
<!-- Contact Heading -->
<div class="page-header text-center">
<h1><i class="fa fa-comment"></i> Kontakt</h1>
<p>Ved spørsmål skriv ein epost i kontaktskjemaet under.</p>
</div>
<!-- Form -->
<!-- use ng-submit to catch the form submission and use our Angular function -->
<form id="contactForm" name="contactForm" novalidate ng-submit="contactForm()" ng-controller="contactController" method="post">
<!-- Name -->
<div class="input-group margin-bottom-sm">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input id="personName" class="form-control" type="text" name="personName" ng-model="contactData.personName" placeholder="Namn *" required />
</div>
<!-- Email -->
<div class="input-group margin-bottom-sm">
<span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
<input id="email" class="form-control" type="email" name="email" ng-model="contactData.email" placeholder="Epost *" required />
</div>
<!-- Subject -->
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-info"></i></span>
<input id="subject" class="form-control" type="text" name="subject" ng-model="contactData.subject" placeholder="Emne *" required />
</div>
<!-- Email Message & Button -->
<div class="input-group">
<div class="input-group-btn">
<!-- Email Message -->
<textarea id="emailMessage" type="text" class="form-control" name="emailMessage" ng-model="contactData.emailMessage" ng-minlength=10 ng-maxlength=300 placeholder="Melding..." required></textarea>
<!-- Button -->
<button id="submit" type="submit" class="btn btn-primary" ng-click="sendMessage('#/path/' + obj.val1 + '/' + 'obj.val2' + '/' + 'obj.val3' + '/' + 'obj.val4')"><i class="fa fa-angle-double-right"></i></button>
debug: {{debug.val}}
</div>
</div>
<br>
</form>
</div>
</div>
</div>
I am not sure if the problem is the ng-click method in the -element and it doesn't work with ng-submit in the -element. May anyone see any other errors in my code?
Here is my controller:
// contact controller
eventApp.controller('contactController', ['$scope', '$http', function($scope, $http) {
$scope.obj = {
val1: '$scope.personName',
val2: '$scope.email',
val3: '$scope.subject',
val4: '$scope.emailMessage'
};
$scope.debug = {
val: ''
};
$scope.sendMessage = function(input) {
$scope.debug.val = input;
};
}]);
I got my inspiration from this link:
concat scope variables into string in angular directive expresssion
If you want to use it that way, pass the object in the function sendMessage(obj), and then in your js just do:
$scope.obj = {
val1: 'personName',
val2: 'email',
val3: 'subject',
val4: 'emailMessage'
};
$scope.sendMessage = function(obj) {
var string = '#/path/' + $scope[obj.val1] + '/' + $scope[obj.val2] + '/' + $scope[obj.val3] + '/' + $scope[obj.val4];
$scope.debug.val = string;
};
JavaScript objects are treated like arrays, so $scope[obj.val1] == $scope.personName, because of the value of $scope.obj.val1.