Angularjs Parse value from input box to controller - html

I have an input box of quantity that the user can change it's value by clicking the - and + buttons. The problem is that if I entre the value directly in the input box I can parse this value to my controller. If I change the value by clicking the buttons + or - I can not parse the value to controller, it keeps always the old value. Can anyone help me?
<button
onclick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty ) && qty > 0 ) result.value--;return false;"
class="reduced items-count"
type="button"
>
<i class="fa fa-minus"> </i>
</button>
<input
type="text"
class="input-text qty"
title="Qty"
maxlength="12"
id="qty"
name="qty"
ng-init="qty='1'"
ng-model="qty"
>
<button
onclick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty )) result.value++;return false;"
class="increase items-count"
type="button"
>
<i class="fa fa-plus"> </i>
</button>
And my controller,
$scope.$watch('qty', function (val) {
if (val) {
alert("qty2:" + val);
}
});

I don't quite understand what you are trying to implement, but you can use ng-click on your buttons to execute some function in your controller.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.qty = 0;
$scope.change = function(value) {
$scope.qty += value;
$scope.changed(); // execute after update
}
$scope.changed = function() {
/*
Do what you want after the update,
but $scope.qty is dynamic anyway
*/
//alert("qty: " + $scope.qty);
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<button ng-click="change(-1)" type="button">-</button>
<input type="number" ng-model="qty" ng-change="changed()" />
<button ng-click="change(1)" type="button">+</button>
<br/>{{qty}}
</div>
</div>
</body>
</html>

This is totally the wrong approach... never use dom methods in angular app like that.
Use ng-click to modify the ng-model property. Also always follow the golden rule of making sure you have a dot in ng-model
angular
.module('app', [])
.controller('Ctrl', function($scope) {
$scope.data = {
qty: 0
}
$scope.updateQty = function(amt) {
$scope.data.qty += amt
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
<button ng-click="updateQty(-1)">-1</button>
<input ng-model="data.qty">
<button ng-click="updateQty(1)">+1</button>
</div>

Related

set the nth-child(n) value of a cloned element jQuery

I want to clone a html element and set values to its child element. My html element is like this.
<div id="avator" class="avator" style="display:none">
<label>gevindu#gmail.com</label>
<i class="fa fa-close"></i>
</div>
I want to clone it and change the css of the clone and and set some values to the label. My jQuery
code,
$(document).ready(function () {
$("#addEmailBtn").click(function () {
var email = $("#emailInput").val();
var $clone = $("#avator").clone();
$clone.children(':nth-child(0)').val(email);
$clone.css("display", "block");
$clone.appendTo("#participantsDiv");
});
});
but its not set the value on the label.
Labels don't have values, that's only for input elements. Use .text().
You don't need :nth-child(1), just use .eq(0).
$(document).ready(function() {
$("#addEmailBtn").click(function() {
var email = $("#emailInput").val();
var $clone = $("#avator").clone();
$clone.children().eq(0).text(email);
$clone.show();
$clone.appendTo("#participantsDiv");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="avator" class="avator" style="display:none">
<label>gevindu#gmail.com</label>
<i class="fa fa-close"></i>
</div>
Email: <input id="emailInput" type="text">
<input type="button" id="addEmailBtn" value="Add email">
<br>
Participants:
<div id="participantsDiv"></div>

How can I create a loop for Chat Bubbles?

I want to develop a loop for chat bubbles. Every time I write a message, a bubble should be created and be on the right. When the chat partner replies, the message should be on the left in the bubble. How can I develop this loop?
My current code is this one:
<div class="Webview">
<div class="message_container" id="myForm"></div>
<form class="send_container">
<input id="textField" type="text">
<p>
<input type="button" id="theButton" value="Nachricht absenden!" onclick="document.getElementById('myForm').innerHTML=document.getElementById('textField').value" />
</p>
<h3>
<div id="div"></div>
</h3>
</form>
</div>
OK, it is not add messages to the DOM in loops, but just add message on Enter on the trigger that sending the message.
If you want to add value from Text Field such as text input,
You probably want to do two steps:
Getting the value from the input
Inject the value into a balloon template (html) and then into the DOM.
Then, you should add Javascript scope into your html or just include js file that contain the following function:
function addMessage() {
// Add XSS validation
const $messages = document.getElementById('myForm');
const $textElement = document.getElementById('textField');
const newMessage = '<div class="message-balloon">' + $textElement.value + '</div>';
$messages.innerHTML += newMessage;
return false;
}
<input type="button" id="theButton" value="Nachricht absenden!" onclick="addMessage()" />
In jQuery it will be like this (in the js scope of course):
$("#theButton").off('click').on('click', function() {
e.preventDefault();
const $messages = $('#myForm');
const $textElement = $('#textField');
const newMessage = '<div class="message-balloon">' + $textElement.value + '</div>';
$messages.html += newMessage;
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="theButton" value="Nachricht absenden!" />
Hope it helps :)
Good luck

Initializing variable in HTML5 for Input tag

Here is the html source code of page that loads array of products:
<div class="container" *ngFor="let product of products">
<div class="product">
<div class="img-container">
<img
//image url
</div>
<div class="product-info">
<div class="product-content">
<h1>{{product.name}}</h1>
<p>{{product.description}}</p>
<p>Price: {{product.price}} $</p>
<p>Quantity:
<button type="button" class="btn btn-danger" (click)="minusQuantity(product)">-</button>
<input type="number" class="input-quantity" [(ngModel)]="product.count"/>
<button type="button" class="btn btn-success" (click)="plusQuantity(product)">+</button>
<div class="buttons">
<a class="button add" (click)="addToCart(product)">Add to Cart</a>
</div>
</div>
</div>
</div>
</div>
When page is loaded, numeric input is empty (there is no value visible inside). Hence clicking on - and + buttons to invoke minusQuantity() and plusQuantity() have no effect on the product.count and displaying it on the page.
I've tried to set default value, but it is overridden by ngModel. If i use only value without ngModel, then input does not react to any changes caused by -/+ buttons (since it's just hardcoded "1").
But if I input e.g. "1" manually on the input, then + and - buttons do work, since there is a value provided, and it works OK.
Question is:
How avoid this issue? Is there any way to initialize input type with some value and then pass it to the product.count correctly? Or the approach should be totally different?
Fragments of components that handle +/- methods:
product.component.ts
plusQuantity(product: ProductModel) {
if (product.count < 99) {
this.cartService.increaseQuantity(product);
}
}
minusQuantity(product: ProductModel) {
if (product.count > 1) {
this.cartService.decreaseQuantity(product);
}
}
cartService.ts
increaseQuantity(product: ProductModel) {
product.count = product.count + 1;
this.orderElement.quantity = product.count + 1;
return product.count;
}
decreaseQuantity(product: ProductModel) {
product.count = product.count - 1;
this.orderElement.quantity = product.count - 1;
return product.count;
}
Use a javascript file with the code:
var cartService = {}
cartService.plusQuantity = function(product) {
product = ProductModel;
if (product.count < 99) {
this.cartService.increaseQuantity(product);
}
};
cartService.minusQuantity = function(product) {
product = ProductModel;
if (product.count > 1) {
this.cartService.decreaseQuantity(product);
}
};
Then it might work!

Unable to add value in string array in angularjs?

I'm trying to add value in students array, but below code isn't working.
js code is --
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.students=[
'Scarlett Johansson','Jennifer Lawrence','Emma Stone','Kristen Stewart'
];
$scope.add = function(name){
$scope.students.push(name);
};
}]);
html code is --
<body ng-app="formExample">
<div ng-controller="ExampleController">
<p ng-repeat="stud in students">
{{stud}}
</p>
</div>
<input type='text' ng-model="name"/>
<button ng-click="add(name);">add</button>
</body>
Your button and input are not included within the div ng-controller="ExampleController" scope.
<body ng-app="formExample">
<div ng-controller="ExampleController">
<p ng-repeat="stud in students">
{{stud}}
</p>
<input type='text' ng-model="name"/>
<button ng-click="add(name);">add</button>
</div> <!-- close div here -->
</body>
You need to push into $scope.students array, as there is no students array defined in the scope:
$scope.add = function(name) {
$scope.students.push(name);
};
$scope.add = function(name) {
$scope.students.push(name);//
};

Why are my inputs not resetting?

The below code generates several forms depending on data returned from the server. Everything generates fine, but after clicking on an AnswerOpenQuestion button the input does not clear/reset. What's going on here?
angularJs code:
var availableInterviewController = function($scope, $http) {
// define initial model
$scope.interviews = [];
// retrieve available interviews
$http.get('/api/UserInterviewsApi/AvailableInterviews')
.success(function(data) {
// update interviews
$scope.interviews = [];
$scope.interviews = data;
});
// define open question answer selection
$scope.Answer = "";
// define multiple choice selection
$scope.selectedChoice = "";
// define answer open question button
$scope.AnswerOpenQuestion = function() {
$scope.Answer = ans;
alert(q.Question + ' and ' + $scope.Answer);
$scope.Answer = ''; // <---This is not clearing/resetting the HTML form inputs
};
// define answer multiple choice button
$scope.AnswerMultipleChoice = function() {
//
};
};
// assign the new controller to the main angular app
myAngApp.controller('availableInterviewCtrl', availableInterviewController);
Html code:
<form class="form-group" ng-repeat="q in inter.Questions">
<fieldset style="display: inline-block;">
<legend>Question {{$index + 1}}</legend>
<!--Open Ended-->
<div class="form-group" ng-show="q.MultipleChoices.length === 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong><br />
</label>
<input name="openQuestion" id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="Answer" />
<button ng-click="AnswerOpenQuestion()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
<!--Multiple Choice Question-->
<div class="form-group" ng-show="q.MultipleChoices.length > 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong>
</label>
<div>
Select an answer:
<label ng-repeat="x in q.MultipleChoices">
<input name="currentChoice" type="radio" value="{{x.Id}}"
ng-model="selectedChoice" />
{{x.Choice}}
</label>
<button ng-click="AnswerMultipleChoice()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
</div>
</fieldset>
</form>
UPDATE - Solution
AngularJs:
// define open question answer selection
$scope.OpenAnswer = { Answer: '' };
// define answer open question button
$scope.AnswerOpenQuestion = function (q, ans) {
$scope.OpenAnswer.Answer = ans;
alert(q.Question + ' and ' + $scope.OpenAnswer.Answer);
// clear the input
$scope.OpenAnswer.Answer = '';
};
Html:
<input id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="OpenAnswer.Answer" />
Don't use the scope as a model instead make an object that wraps the data model and assign it to a property of the scope.
$scope.myModel = {Answer:''}
Also don't use value in most cases ngmodel is all you need for two way binding.
In js strings are immutable so the original reference is not being updated instead a new string is being made, the digest cycle won't see this as a change to the original string.