can't reset form input using ng-click - javascript

I want to reset input value using ng-click to add it's value to a $scope var then reset the input value
here is my html
<form ng-controller="questionsCTRL" class="ui large form" name="questionForm" ng-submit="addSurvey(questionForm)" novalidate>
<div class="ui segment" id="quest-answers">
<div class="two fields">
<div class="field">
<label>Add New Answer</label>
<div class="ui action input">
<input type="text" required name="answers" ng-model="answers"
ng-required="true" ng-minlength="5" placeholder="answer...">
<button type="button"
ng-click="addAnswer(questionForm.answers.$viewValue)"
ng-disabled="questionForm.answers.$invalid"
class="ui teal right labeled icon button">
<i class="add icon"></i>
Add
</button>
</div>
<small ng-show="questionForm.answers.$invalid" class="ui meta teal">Answers is required</small>
</div>
</div>
<div class="ui grid">
<div class="row">
<div class="eleven wide column">
<div class="field">
<div class="ui attached segment" ng-repeat="answer in answerGroup">
{{answer.text}}
<a href class="ui right floated link"><i class="circular delete icon"></i></a>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
and this is controller content
UIASSIGN1.controller('questionsCTRL', function($scope , $rootScope , $state, $stateParams , $http ) {
// #dummy controller
$rootScope.sectorName = 'Questions';
var _SID = $stateParams.id;
$scope.answerGroup = [];
$http.get("api/survey/survey.json")
.then(function(response) {
var surveyArray = response.data;
$scope.surveyArray = [];
for (var i = 0; i < surveyArray.length; i++) {
var thisItem = surveyArray[i];
var thisElm = {name:thisItem.name,value:parseInt(thisItem._id)};
$scope.surveyArray.push(thisElm)
}
});
$scope.addAnswer = function(answer){
var inArray = {
text : answer
};
$scope.answerGroup.push(inArray);
$scope.questionForm.answers = {};
}
});
this ng-click adds value to $scope.userGroups but it doesn't reset the form input value only resets the $scope.questionForm.answers value to {}

As I mentioned in the comments the value of $scope.answer is mapped to this element:
<input type="text" required name="answers" ng-model="answers"
ng-required="true" ng-minlength="5" placeholder="answer...">
The ng-model="answers" means to define a variable called answers in the scope. Then in angular you can access it with $scope.answers, that is why:
$scope.answers = "";
Will reset the input element.

You could do it like this. Define the answer on the scope
$scope.theAnswer = '';
Set this as your ngModel for the input field:
ng-model="theAnswer"
Simplify your ng-click like this and add the answer to the array directly in the controller and then cleanup the answer:
ng-click="addAnswer()"
$scope.addAnswer = function(){
var inArray = {
text : $scope.theAnswer
};
$scope.answerGroup.push(inArray);
$scope.theAnswer = '';
}

Related

How to send Javascript array as Json combined with a html form?

I am creating a restaurant menu app that a waiter can use to input orders.
I have a Js array called itemOrderList that I am storing item names in. I want to be able to send that list of item names as Json array with customer name form input field and item price to back end to be stored in my DB. I am having issues going about doing this. What should I do? Google dev tools says "ReferenceError: itemOrderList is not defined" where I am trying to stringify the Js array.
AngularJs code
.controller('orderAddCtrl', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.itemOrderList = [];
$scope.totalItemPrices = 0;
$scope.addOrderToList = function (item) {
console.log(item.itemName);
$scope.addPricesToTotalItemPrices(item.itemPrice);
$scope.itemOrderList.push(item.itemName);
};
$scope.addPricesToTotalItemPrices = function (price) {
console.log(price);
$scope.totalItemPrices += price ;
};
$scope.removeFromOrderToList = function (index) {
console.log(index);
$scope.itemOrderList.splice(index, 1);
};
$scope.createOrder = function (order) {
var myJson = JSON.stringify(itemOrderList);
order.orderPrice = totalItemPrices;
order.orderItems = myJson;
dataService.addOrder(order).then(function () {
$location.path('/');
});
};
Html
<form class="form-horizontal" ng-init="getItems()">
<div class="row">
<div class="col-6">
<div class="form-group">
<div>
<input ng-click="createOrder(order)" class="btn btn-success" value="Create" />
Back
</div>
</div>
</div>
<div class="col-6">
<div class="form-group">
<label class="control-label">Customer Name</label>
<div class="col-lg-10">
<input type="text" class="form-control" ng-model="order.customerName" />
</div>
</div>
</div>
</div>
<div>
<h1>Total Price: ${{totalItemPrices}}</h1>
</div>
<div class="">
<h2>Food Items</h2>
<div class="row">
<button class="btn btn-success col-3" ng-repeat="i in Items" ng-click="addOrderToList(i)">{{i.itemName}}</button>
</div>
</div>
<div class="">
<h2>Order Items</h2>
<ul>
<li ng-repeat="i in itemOrderList track by $index">
<p>{{i}}/<p>
<button ng-click="removeFromOrderToList($index)">Remove</button>
</li>
</ul>
</div>
</div>
</form>
I bet you need to specify you're using vars declared in $scope as so...
$scope.createOrder = function (order) {
var myJson = JSON.stringify($scope.itemOrderList);
order.orderPrice = $scope.totalItemPrices;
order.orderItems = myJson;
dataService.addOrder(order).then(function () {
$location.path('/');
});
};

Firebase Chat change reference with javascript

I am trying out how to incorporate firebase with angular in such a way that the user is able to change the "Channel" of the chat via selecting from a dropdownlist.
This is the code that I have at the moment:
Note: The channel attribute is defined in another portion of code, and the entire page is loaded only once.
app.controller('mychat', function($scope, $firebaseArray) {
var d = new Date();
var today = d.getDate()+d.getMonth()+d.getYear();
var txt = document.getElementById('txtFBMsgs'); //store id of textbox
//Query
var ref = firebase.database().ref().child(channel)
$scope.fbmessages = $firebaseArray(ref);
$scope.send = function() {
if (txt.value != ""){ //check if textbox contains any message
$scope.fbmessages.$add({
sender: sender,
message: $scope.messageText,
date: Date.now()
})
txt.value = ""; //reset value of textbox
}
}
})
and here is my html portion:
<div class="card mb-1 col-md-3" ng-controller="mychat" id="myDiv">
<div class="card-body" style="overflow-x: hidden; overflow-y:scroll; min-height:60vh; max-height:64vh;">
<div>
<p ng-repeat="m in fbmessages"> {{m.date | date:'short'}} - {{m.sender}}: <br> {{m.message}}</p>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-9">
<input type="text" id = "txtFBMsgs" class="form-control" placeholder="Message here..." ng-model="messageText" onkeydown = "if (event.keyCode == 13) document.getElementById('sendBtn').click()">
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-primary btn-block" id="sendBtn" ng-click="send()">Send</button>
</div>
</div>
basically, it is a div that displays the chat messages, and an input box which is able to send the message to firebase.
Can I change the 'Channel' dynamically via javascript, such as on an onchange in a DDL?

creating textbox element dynamically and bind different model

I am working in angular js application, where i need to create textbox with buttons dynamically that means
<div class="col-sm-4 type7" style="font-size:14px;">
<div style="margin-bottom:5px;">NDC9</div>
<input type="text" name="ndc9" class="form-control txtBoxEdit" ng-model="ndc9">
</div>
<div class="col-sm-4 type7 " style="font-size:14px;">
<div style="padding-top:20px; display:block">
<span class="red" id="delete" ng-class="{'disabled' : 'true'}">Delete</span> <span>Cancel </span> <span id="addRow" style="cursor:pointer" ng-click="ndcCheck(0)">Add </span>
</div>
</div>
this will create below one
i will enter some value in above textbox and click add ,it needs to be created in next line with same set of controls that means (textbox with above 3 buttons need to be created again with the entered value).
Entering 123 in first textbox and click add will create new textbox with delete,cancel,add button with entered value.
Again am adding new value 243 then again it needs to create new textbox down to next line with the entered value (and also the same controls).
finally i want to get all the entered values. how can i achieve this in angular js
You could use ng-repeat with an associative array. Add Would basically push the model value to an array and and also an empty object in the array.
<div ng-repeat ="ndc in NDCarray">
<div class="col-sm-4 type7" style="font-size:14px;">
<div style="margin-bottom:5px;">NDC9</div>
<input type="text" name="ndc9" class="form-control txtBoxEdit" ng-model="ndc.val">
</div>
</div>
<div class="col-sm-4 type7 " style="font-size:14px;">
<div style="padding-top:20px; display:block">
<span class="red" id="delete" ng-class="{'disabled' : 'true'}" ng-click="NDCdelete($index)">Delete</span>
<span>Cancel </span>
<span id="addRow" style="cursor:pointer" ng-click="NDCadd ()">Add </span>
</div>
</div>
</div>
In the controller:
$scope.NDCarray = [{val: ''}];
$scope.NDCadd = function() {
$scope.NDCarray.unshift(
{val: ''}
);
};
$scope.NDCdelete = function(index) {
$scope.NDCarray.splice(index, 1);
};
Plunker: https://plnkr.co/edit/3lklQ6ADn9gArCDYw2Op?p=preview
Hope this helps!!
<html ng-app="exampleApp">
<head>
<title>Directives</title>
<meta charset="utf-8">
<script src="angular.min.js"></script>
<script type="text/javascript">
angular.module('exampleApp', [])
.controller('defaultCtrl', function () {
vm = this;
vm.numbers = [1, 2, 3];
vm.add = function (number) {
vm.numbers.push(number);
}
vm.remove = function (number) {
var index = vm.numbers.indexOf(number);
if(index>-1){
vm.numbers.splice(index, 1);
}
}
});
</script>
</head>
<body ng-controller="defaultCtrl as vm">
<div ng-repeat="num in vm.numbers">
<span>Number : {{num}}</span>
</div>
<div>
<input type="number" ng-model="vm.newNumber">
<button ng-click="vm.add(vm.newNumber)">Add</button>
<button ng-click="vm.remove(vm.newNumber)">Remove</button>
</div>
</body>
</html>

Form data not showing after post in AngularJS

I am trying to post a form data but the content are not updated on the UI.
The following code is working it does post the data but the tags are not updated in the {{tag.Title}}.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var new1 = data;
$scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
<div class="row" data-ng-repeat="tagsByType in consultantCv.TagsbyTypes" ng-init="init('tag',2000)">
<div class="col-md-12">
<hr />
<h2>
<i class="icons8-{{tagsByType.CssClass}}" aria-hidden="true"></i>{{tagsByType.Title}}
</h2>
<div class="tags">
<div class="input-group" ng-controller="consultantController">
<div ng-repeat="tag in tagsByType.Tags" class="tag label label-success">
{{tag.Title}}
<a class="close" href ng-click="removeTag(tag)">×</a>
</div>
<form ng-submit="saveTag(Title,tagsByType.Id)" role="form">
<input type="text" ng-model="Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>
</div>
</div>
</div>
</div>
Push your data as object with same property name.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var newData = {
Title : data,
}
$scope.consultantCv.TagsbyTypes[0].Tags.push(newData);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
Found the issue was that tagsType was not passed to the controller.
Fixed it by the following code
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(result){
TagTypeId.Tags.push(result);
$scope.consultantCv.TagsbyTypes.Tags.push(newData);
//$scope.consultantCv.TagsbyTypes[0].Tags.push(new1);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
};
<form ng-submit="saveTag(tag.Title,tagsByType)" role="form">
<input type="text" ng-model="tag.Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>

How to clear angularJS form after submit?

I have save method on modal window once user execute save method i want to clear the form fields, I have implemented $setPristine after save but its not clearing the form. How to achieve that task using angularJS ?
So far tried code....
main.html
<div>
<form name="addRiskForm" novalidate ng-controller="TopRiskCtrl" class="border-box-sizing">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="topRiskName" class="required col-md-4">Top Risk Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="topRiskName" ng-model="topRiskDTO.topRiskName"
name="topRiskName" required>
<p class="text-danger" ng-show="addRiskForm.topRiskName.$touched && addRiskForm.topRiskName.$error.required">Top risk Name is required field</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="issuePltfLookUpCode" class="col-md-4">Corresponing Issue Platform:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="issuePltfLookUpCode"
k-option-label="'Select'"
ng-model="topRiskDTO.issuePltfLookUpCode"
k-data-source="issuePltDataSource"
id="issuePltfLookUpCode">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">Issue/Risk Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="issueNo" ng-model="topRiskDTO.issueNo"
name="issueNo">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addRiskForm.$invalid" ng-click="submit()">Save</button>
<button class="btn btn-primary pull-right" ng-click="handleCancel">Cancel</button>
</div>
</form>
</div>
main.js
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
$scope.$emit('refreshTopRiskGrid');
$scope.addRiskForm.$setPristine();
});
};
});
Hey interesting question and I have messed around with it and I have come up with something like this (I have abstracted the problem and simplified it, it is up to you to implent it to your likings). Likely not super elegant but it does the job: Fiddle
<div ng-app="app">
<div ng-controller="main">
<form id="form">
<input type="text" />
<input type="text" />
</form>
<button ng-click="clear()">clear</button>
</div>
</div>
JS
angular.module("app", [])
.controller("main", function ($scope) {
$scope.clear = function () {
var inputs = angular.element(document.querySelector('#form')).children();
angular.forEach(inputs, function (value) {
value.value="";
});
};
})
Hope it helps.
Edit
If you give all your inputs that must be cleared a shared class you can select them with the querySelector and erase the fields.
Refer to this page: http://blog.hugeaim.com/2013/04/07/clearing-a-form-with-angularjs/
$setPristine will only clear the variables not the form. To clear the form set their values to blank strings
<script type="text/javascript">
function CommentController($scope) {
var defaultForm = {
author : "",
email : "",
comment: ""
};
$scope.postComments = function(comment){
//make the record pristine
$scope.commentForm.$setPristine();
$scope.comment = defaultForm;
};
}
</script>
Clear topRiskDTO
Looking at your example, seems that clearing topRiskDTO will give you this result.
for instance:
$scope.submit = function(){
// ...
// The submit logic
// When done, Clear topRiskDTO object
for (var key in $scope.topRiskDTO)
{
delete $scope.topRiskDTO[key];
}
};
You have to manually reset the data. See this website for more info.
You also have to call
$form.$setPristine()
To clear all the css classes.

Categories

Resources