Fields values generated using ng-repeat is not getting while submit - angularjs

Template for form submission. This page will display the form template. Initially it shows the TItle,Full Name. On clicking the 'Add Tags' link new input fields is been generated for entering tags.
On submit, the field input(story.tag) is not been included on RequestPayload
<form novalidate ng-submit="save()">
<div>
<label for="title">Title</label>
<input type="text" ng-model="story.title" id="title" required/>
</div>
<div>
<label for="firstName">Full Name</label>
<input type="text" ng-model="story.fullname" id="fullname" required/>
</div>
<div ng-controller="Note" >
<div ng-repeat="story in items ">
<label>Tag {{$index+1}}:</label>
<input type="text" ng-model="story.tag" id="tag" required/>
</div>
<a ng-click="add()">Add Tags</a>
</div>
<button id="save" class="btn btn-primary">Submit Story</button>
</form>
script :- app.js
angular.module("getbookmarks", ["ngResource"])
.factory('Story', function ($resource) {
var Story = $resource('/api/v1/stories/:storyId', {storyId: '#id'});
Story.prototype.isNew = function(){
return (typeof(this.id) === 'undefined');
}
return Story;
})
.controller("StoryCreateController", StoryCreateController);
function StoryCreateController($scope, Story) {
$scope.story = new Story();
$scope.save = function () {
$scope.story.$save(function (story, headers) {
toastr.success("Submitted New Story");
});
};
}
//add dynamic forms
var Note = function($scope){
$scope.items = [];
$scope.add = function () {
$scope.items.push({
inlineChecked: false,
tag: "",
questionPlaceholder: "foo",
text: ""
});
};
}

The story object inside ng-repeat is in another scope. This JSFiddle should do what you are looking for.
<div ng-app>
<div ng-controller="NoteCtrl">
<form novalidate ng-submit="save()">
<div>
<label for="title">Title</label>
<input type="text" ng-model="story.title" id="title" required/>
</div>
<div>
<label for="firstName">Full Name</label>
<input type="text" ng-model="story.fullname" id="fullname" required/>
</div>
<div ng-repeat="story in items">
<label>Tag {{$index+1}}:</label>
<input type="text" ng-model="story.tag" required/>
</div> <a ng-click="add()">Add Tags</a>
<button id="save" class="btn btn-primary">Submit Story</button>
</form>
<div ng-repeat="test in items">
<label>Tag {{$index+1}}: {{test.tag}}</label>
</div>
</div>
</div>
The NoteController:
function NoteCtrl($scope) {
$scope.story = {};
$scope.items = [];
$scope.story.tag = $scope.items;
$scope.add = function () {
$scope.items.push({
inlineChecked: false,
tag: "",
questionPlaceholder: "foo",
text: ""
});
console.log($scope.story);
};
}

Related

My AngularJS 1.5 component called booking-info isn't populating the input fields in my form with booking data

I have a form inside a bookingEdit component and a bookingInfo component containing the form's input fields. The fields inside bookingInfo component aren't being populated with the booking data. How can I get these fields to be populated using my booking-info and booking-edit components?
booking-edit.template.html
<form name="$ctrl.form" ng-submit="$ctrl.updateBooking()">
<fieldset>
<legend>Edit Booking</legend>
<booking-info booking="$ctrl.booking"></booking-info>
<button class="btn btn-success" type="submit">Save</button>
</fieldset>
</form>
booking-edit.component.js
'use strict';
angular.
module('bookingEdit').
component('bookingEdit', {
templateUrl: 'booking-edit.template.html',
controller: ['BookingService','$location',
function (BookingService,$location) {
let self = this;
self.$routerOnActivate = function(next, previous) {
self.booking = BookingService.get({ id: next.params.id });
};
self.updateBooking = function () {
BookingService.update({ id: self.booking.bookingId }, self.booking)
.$promise
.then(
function () {
$location.path('/list');
},
function (error) {
}
);
};
}
]
});
booking-info.component.js
angular.module('app').
component('bookingInfo', {
templateUrl: 'booking-details.html',
bindings: {
booking:'<'
},
controller: function(){
let self = this;
}
});
booking-details.html
<div class="form-group">
<label for="contactName">Contact Name</label>
<input required type="text" class="form-control" ng-model="booking.contactName">
</div>
<div class="form-group">
<label for="contactNumber">Contact Number</label>
<input required type="tel" class="form-control" ng-model="booking.contactNumber">
</div>
You seem to forgot the $ctrl in booking-details.html
<div class="form-group">
<label for="contactName">Contact Name</label>
<input required type="text" class="form-control" ng-model="$ctrl.booking.contactName">
</div>
<div class="form-group">
<label for="contactNumber">Contact Number</label>
<input required type="tel" class="form-control" ng-model="$ctrl.booking.contactNumber">
</div>

angular dropdown option value login data object for user roles in database

So I am finding myself at a bit of a roadblock on taking grabbing a value from a dropdown option in angular for creating one of two specific user roles for my postgreSQL database.
I have many inputs (several exclusive to each dropdown) for creating users such as:
1. username
2. password
3. email
etc...
all are easily passed into a user object within my angular controller using ng-model to reference them. What I am trying to achieve with my form is for each option of my select dropdown to log a specific value to the key of role within my user object so i can store that to a specific record within the field of 'role'.
HTML Snippit:
<form name="createAccount" ng-submit="create(this)">
<select ng-model="showRole" class="form-control" ng-options="role.abbreviation as role.name for role in roles">
<option value="">Choose One</option>
</select>
<div ng-switch="showRole">
<div ng-switch-when="agt">
<div>
<label for="firstName">First Name</label>
<input type="text" ng-model="createAccount.firstName">
</div>
<div>
<label for="lastName">Last Name</label>
<input type="text" ng-model="createAccount.lastName">
</div>
<div>
<label for="email">E-mail</label>
<input type="e-mail" ng-model="createAccount.email">
</div>
<div>
<label for="company">Agency</label>
<input type="text" ng-model="createAccount.company">
</div>
<div>
<label for="createAccount-username">Username</label>
<input type="text" ng-model="createAccount.username">
</div>
<div>
<label for="createAccount-password">Password</label>
<input type="password" ng-model="createAccount.password">
</div>
<div>
<label for="createAccount-passwordConfirm">Password Confirm</label>
<input type="password" ng-model="createAccount.passwordConfirm">
</div>
</div>
<div ng-switch-when="pmt">
<div>
<label for="firstName">First Name</label>
<input type="text" ng-model="createAccount.firstName">
</div>
<div>
<label for="lastName">Last Name</label>
<input type="text" ng-model="createAccount.lastName">
</div>
<div>
<label for="email">E-mail</label>
<input type="e-mail" ng-model="createAccount.email">
</div>
<div>
<label for="company">Venue</label>
<input type="text" ng-model="createAccount.company">
</div>
<div>
<label for="createAccount-username">Username</label>
<input type="text" ng-model="createAccount.username">
</div>
<div>
<label for="createAccount-password">Password</label>
<input type="password" ng-model="createAccount.password">
</div>
<div>
<label for="createAccount-passwordConfirm">Password Confirm</label>
<input type="password" ng-model="createAccount.passwordConfirm">
</div>
</div>
<div>
<button>Create Account</button>
</div>
and Angular Controller:
(function(){
var LoginController = function ($scope, $http ) {
$scope.pageID = "Login/Register Page";
$scope.create = (form) => {
console.log('create form submitted');
const user = {
firstName: form.createAccount.firstName,
lastName: form.createAccount.lastName,
email: form.createAccount.email,
company: form.createAccount.company,
username: form.createAccount.username,
password: form.createAccount.password,
}
$http.post('/users/create', user)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
}
$scope.loginSubmitted = (form) => {
console.log('login form submitted');
}
$scope.roles = [{ abbreviation: 'agt', name: "Agent"},{abbreviation: 'pmt', name: "Promoter"}];
this.setTab = function(setTab) {
this.tab = setTab;
};
this.isSelected = function(checkTab) {
return this.tab === checkTab;
};
this.notSelected = function(checkTab) {
return !(this.isSelected(checkTab));
};
this.getTab = function() {
return this.tab;
};
this.setIsDefault = function() {
this.isDefault = true;
};
this.getIsDefault = function() {
return this.isDefault;
};
}
angular.module('avp')
.controller('LoginController', LoginController);
LoginController.$inject = ['$scope', '$http'];
}())
OK. I am kinda ashamed of the fact that I asked such a dumb question but it is event more satisfying to figure out the answer and answer my own question on here for the first time.
All I had to do was new property in user object with form.showRole. WHOOO Crazy!
Overthinking it FTW!

How to reset Bootstrap Form

Here im using Bootstrap validations with AngularJs when my form is submitted the columns is reset but its shows all validation..But my aim is its should not display validations
Bootstrap
<div class="modal" id="modal1">
<div class="modal-dialog">
<div class="modal-content">
<form name="f1" novalidate ng-submit="Save(Auth.emp)">
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-sm-4">
Email
</div>
<div class="col-sm-8">
<input type="text" name="email" class="form-control" ng-model="Auth.Email" ng-class="Submitted?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.email.$dirty ||Submitted) && f1.email.$error.required">Email REq</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-4">
Password
</div>
<div class="col-sm-8">
<input type="text" name="psw" class="form-control" ng-model="Auth.Password" ng-class="Submitted?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.psw.$dirty ||Submitted) && f1.psw.$error.required">Password REq</span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" value="{{LoginAction}}" />
</div>
</form>
</div>
</div>
</div>
AngularCode.Js
$scope.Save = function (emp) {
if ($scope.LoginAction = "Login") {
$scope.Submitted = true;
if ($scope.isFormValid == true) {
var ss = {
Email: $scope.Auth.Email,
Password: $scope.Auth.Password,
}
var xxer = myServices.GetLogin(ss);
xxer.then(function (msg) {
$scope.msg = msg.data;
$('#modal2').modal('show')
Reset();
})
}
}
}
Reset
function Reset() {
$scope.Email = '';
$scope.Password = '';
}
I think you looking for this:
function Reset() {
$scope.Auth.Email = ''
$scope.Auth.Password = '';
}
You can set a model at the same level as the form tag and make all other inputs sub properties. Then set form model at the root level to an empty object when you click on reset. Here's a codepen.
function exampleController($scope) {
$scope.reset = function() {
$scope.form = {};
};
}
angular
.module('app', [])
.controller('exampleController', exampleController);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div class="row" ng-app="app" ng-controller="exampleController">
<form novalidate ng-model="form">
<input ng-model="form.email" type="email" />
<input ng-model="form.password" type="password" />
</form>
<button ng-click="reset()">Reset</button>
<pre>{{form}}</pre>
</div>

Firebase angularfire child.$asObject give properties undefined

I've got this code:
factory
app.factory('Items', function($firebase,FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL);
var items = $firebase(ref.child('items')).$asArray();
var Item = {
all: function () {
return items;
},
create: function (item) {
return items.$add(item);
},
get: function (itemId) {
return $firebase(ref.child('items').child(itemId)).$asObject();
},
update: function (itemId, item) {
return $firebase(ref.child('items').child(itemId)).update(item);
},
delete: function (item) {
return items.$remove(item);
}
};
return Item;
});
route
app.config(function($stateProvider) {
$stateProvider
.state('items_update', {
url: '/items/update/:id',
templateUrl: 'views/items/form.html',
controller:'ItemsUpdateController',
resolve:{
item:function(Items,$stateParams){
return Items.get($stateParams.id);
}
}
})
});
controller
app.controller('ItemsUpdateController', function ($scope, item, $state) {
$scope.item = item;
console.log($scope.item.url);
$scope.add = function() {
Items.update($scope.item).then(function () {
$state.transitionTo('items');
});
}
});
why console.log($scope.item.url); give me undefined ?
but in the view I've got all the data
html
<form class="form-horizontal" role="form" name="form" data-ng-submit="add()">
<div class="form-group">
<input type="text" name="title" tabindex="1" class="form-control" placeholder="{{ 'items.form.title' | translate }}" data-ng-model="item.title" required="required" data-ng-minlength="3" data-ng-maxlength="25" user-feedback />
</div>
<div class="form-group">
<input type="text" name="ingredients" tabindex="2" class="form-control" placeholder="{{ 'items.form.ingredients' | translate }}" data-ng-model="item.ingredients" required="required" ng-pattern="/^\w(\s*,?\s*\w)*$/" user-feedback />
</div>
<div class="form-group">
<input type="text" name="price" tabindex="3" class="form-control" placeholder="{{ 'items.form.price' | translate }}" data-ng-model="item.price" required="required" data-smart-float user-feedback />
</div>
<div class="form-group">
<button type="button" tabindex="4" class="btn btn-default btn-lg" item="item" data-uploader>{{ 'items.form.upload' | translate }}</button>
<input type="text" name="url" style="display:none;" required="required" data-ng-model="item.url" />
</div>
<div class="form-group form-no-required clearfix">
<div class="pull-right">
<button type="submit" tabindex="5" class="btn btn-primary" data-ng-disabled="form.$invalid">{{ 'items.form.submit' | translate }}</button>
</div>
</div>
</form>
ENDS UP
as in the #Frank van Puffelen comment
I worked it out with:
app.controller('ItemsUpdateController', function($scope, item, $state) {
item.$loaded().then(function(data) {
$scope.item = data;
console.log($scope.item.url);
});
$scope.add = function() {
Items.update($scope.item).then(function() {
$state.transitionTo('items');
});
}
});
This is because by the time your console.log($scope.item.url); runs, the data hasn't been loaded from Firebase yet. Angular listens for a notification from Firebase/AngularFire to know when the data has loaded and then updates the view.
Also see angularfire - why can't I loop over array returned by $asArray? and Trying to get child records from Firebase.

AngularJS select not updating after json push

I have the following controller:
function userControl($scope,$http) {
$scope.users = [
{"id":"0","name":"User1","roles":[{}]},
{"id":"1","name":"User2","roles":[{}]},
]
$scope.addUser = function() {
var nextid = $scope.getNextId();
$scope.users.push({id:nextid,name:$scope.userName});
$scope.userName = '';
//$apply();
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
And the following HTML:
<h2>Users</h2>
<div ng-controller="userControl">
<div ng-repeat="user in users">
{{user.id}} : {{user.name}}
</div>
<form ng-submit="addUser()">
<input type="text" ng-model="userName" placeholder="User Name" />
<input type="submit" value="add">
</form>
</div>
<h2>Add role to user</h2>
<div ng-controller="userControl">
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users"></select>
<input type="submit" value="add">
</form>
</div>
When I add a user in the addUser() function I can see the user is added since it's listed under the ng-repeat, however the user name does not appear in the select box.
This is because you use the same controller twice. This creates two separate scopes. When you add a user in one scope it doesn't get added in the second scope. The fix is simple, join the code in one scope:
<div ng-controller="userControl">
<h2>Users</h2>
<div>
<div ng-repeat="user in users">
{{user.id}} : {{user.name}}
</div>
<form ng-submit="addUser()">
<input type="text" ng-model="userName" placeholder="User Name" />
<input type="submit" value="add">
</form>
</div>
<h2>Add role to user</h2>
<div>
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users"></select>
<input type="submit" value="add">
</form>
</div>
</div>
An alternative approach is to create a Service since services are singletons:
module.factory('Users',function(){
var users = [
{"id":"0","name":"User1","roles":[{}]},
{"id":"1","name":"User2","roles":[{}]},
];
return {
users:users,
add:function(user){
users.push(user);
}
}
});
function userControl($scope, Users) {
$scope.users = Users.users;
$scope.addUser = function() {
var nextid = $scope.getNextId();
Users.add({id:nextid,name:$scope.userName});
$scope.userName = '';
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
This will work with your original markup.

Resources