how to pass value to an angular function using ng-click - javascript

I'm trying to pass the value of the ng-model="alertThreshold.value" but when I click on <a class="spin-up" data-spin="up" ng-click = "getAlertThreshold(alertThreshold.value)"><i class="fa fa-caret-up"></i></a> or <a class="spin-down" data-spin="down ng-click = "getAlertThreshold(alertThreshold.value)"" ><i class="fa fa-caret-down"></i></a>
it just call the function without updating the value, the value is always = 10.
<div class="input-group spinner" data-trigger="spinner">
<input type="text" class="form-control text-center" value="0" data-rule="quantity" ng-model="alertThreshold.value" min="0" max="50" ng-change ="getAlertThreshold(alertThreshold.value)">
<div class="input-group-addon">
<a class="spin-up" data-spin="up" ng-click = "getAlertThreshold(alertThreshold.value)"><i class="fa fa-caret-up"></i></a>
<a class="spin-down" data-spin="down" ng-click = "getAlertThreshold(alertThreshold.value)"><i class="fa fa-caret-down"></i></a>
</div>
</div>
and in my controller:
$scope.alertThreshold = {
value: 10
};
$scope.getAlertThreshold = function(value){
console.log("value:",value)
$scope.alertThreshold.value = value;
}

ng-click = "getAlertThreshold(++alertThreshold.value)" ng-click = "getAlertThreshold(--alertThreshold.value)" may resolve the issue.

The value of $scope.alertThreshold.value is always the same because take the value of the input. It's like $scope.alertThreshold.value = $scope.alertThreshold.value every ng-click or ng-change

Related

How to change the file input value after selected using javascript?

<div class="form-group">
<span class='btn btn-file btn-block btn-default'> <i class='pe pe-7s-video'> </i> Choose from Library
<input type='file' class='form-control' name='answer_video' accept='video/*' capture='camera' placeholder='Record' id='answer_video'></span>
</div>
How to change the value "Choose from Library" to "video selected" after choosing file through file input using javascript
On change event, check if the this.files are more than 0.
Demo
document.querySelector( "[name='answer_video']" ).addEventListener( "change", function(){
if ( this.files.length > 0 )
{
this.parentNode.querySelector(".videoLabel").innerHTML = "file selected";
}
else
{
this.parentNode.querySelector(".videoLabel").innerHTML = "Choose from Library";
}
});
<div class="form-group">
<span class='btn btn-file btn-block btn-default'> <i class='pe pe-7s-video'> </i> <span class="videoLabel">Choose from Library</span>
<input type='file' class='form-control' name='answer_video' accept='video/*' capture='camera' placeholder='Record' id='answer_video'></span>
</div>
You can use EventListener DOMContentLoaded and onchange do something
reference here
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('[type="file"]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
// You can use “this” to refer to the selected element.
document.getElementById('video_option').innerHTML = 'video selected';
}
<div class="form-group">
<span class='btn btn-file btn-block btn-default'> <i class='pe pe-7s-video'> </i><span id='video_option'> Choose from Library</span>
<input type='file' class='form-control' name='answer_video' accept='video/*' capture='camera' placeholder='Record' id='answer_video'></span>
</div>
you may take help with jquery, hope it will help you.
$("input[type='file'][name='answer_video']").change(function(){
var id = $(this).attr("id");
var thisVal = document.getElementById(id).files[0].name;
var nameBox = '<div class="fileContainer"><span class="docFileName">'+thisVal+'</span><span class="glyphicon glyphicon-remove" onclick=removeAttachment("'+id+'")>X</span></div>';
$(this).before(nameBox).hide();
});
function removeAttachment(id){
$("#"+id).val("").show();
$(".fileContainer").remove();
}
You only need to use the onchange function with your input.
function changeName(){
document.getElementById("change").innerHTML = "changeName"
}
<div class="form-group">
<span id="change" class='btn btn-file btn-block btn-default'> <i class='pe pe-7s-video'> </i> Choose from Library
</span>
<input type='file' class='form-control' name='answer_video' placeholder='Record' id='answer_video' onchange="changeName()">
</div>

ng-model doesnt bind with text field

Consider the following JS
angular.module('myApp')
.controller('HeaderCtrl', function($scope) {
$scope.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.searchBooking);
//$location.path('/bookings/' + $scope.searchBooking);
//delete($scope.searchBooking);
}
$scope.printValue = function() {
console.log($scope.searchBooking);
}
}
);
And the following HTML
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Testing" ng-model="searchBooking" ng-change="printValue()">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
My problem is that when the page loads, "test" is written in the text field, but when I change the field or press the button, nothing happens (console says "test" on every change or button click. Anyone know what I did wrong?
Try to wrap the value in an object. Objects are passed by reference, but simple values are passed as a copy of that value. It happened to me too several times.
Try this approach
$scope.myObject.searchBooking = "test"
So the full code will look like this
angular.module('myApp')
.controller('HeaderCtrl', function($scope) {
$scope.myObject.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.myObject.searchBooking);
//$location.path('/bookings/' + $scope.myObject.searchBooking);
//delete($scope.myObject.searchBooking);
}
$scope.printValue = function() {
console.log($scope.myObject.searchBooking);
}
}
);
and the html
<input type="text" class="form-control" placeholder="Testing" ng-model="myObject.searchBooking" ng-change="printValue()">
Find this fiddle which is having ng-model binding in ng-change.
HTML
<div ng-controller="MyCtrl">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Testing" ng-model="searchBooking" ng-change="printValue()">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</div>
Angular controller
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.searchBooking = "test";
$scope.goToBooking = function() {
console.log($scope.searchBooking);
//$location.path('/bookings/' + $scope.searchBooking);
//delete($scope.searchBooking);
}
$scope.printValue = function() {
console.log($scope.searchBooking);
}
}

angular bootstrap btn-radio does not change value

I have the following html:
<label class="btn btn-sm btn-info" ng-model="radioModel" btn-radio="'title'"><i class="fa fa-check text-active"></i> Jobprofil</label>
<label class="btn btn-sm btn-success" ng-model="radioModel" btn-radio="'division'"><i class="fa fa-check text-active"></i> Afdelinger</label>
For this i have the following $scope variable:
$scope.radioModel = 'title';
And a listner for changes:
$scope.$watch('radioModel', function (newValue, oldValue) {
if(newValue == 'title'){
$scope.dataset = $scope.titleSet;
}
else if(newValue == 'division'){
$scope.dataset = $scope.divisionDataset;
}
}, true);
However whenever i click either of the elements the value does not change (or atleast the $watch is not being called)
So what am i doing wrong?
It seems everything is OK in your snippet, $watcher is working fine, check the plunker:
http://plnkr.co/edit/c4bwHh8acsQZ2Y7RxCU9?p=preview

Adding Angular UI Datepicker dynamically

In my project I need to add dynamic amount of datepickers to the page.
I tried to do it this way (Plunker):
Script:
var app = angular.module('plunker', ['ui.bootstrap']);
app.controller('MainCtrl', function($scope) {
$scope.openDatePicker = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: "yy",
startingDay: 1,
format: "shortDate"
};
$scope.details = [{
"parameterValue": "2015-08-12"
}, {
"parameterValue": "2015-08-12"
}, {
"parameterValue": "2015-08-12"
}, {
"parameterValue": "2015-08-12"
}];
});
HTML:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="script.js"></script>
</head>
<body>
<div ng-controller="MainCtrl">
<form name="detailsForm" novalidate ng-submit="submitForm(detailsForm.$valid)">
<div ng-repeat="item in details" class="input-group">
<input ng-model="item.parameterValue" type="text" class="form-control" id="datePickerItem" datepicker-popup="shortDate"
is-open="opened" datepicker-options="dateOptions" current-text="Today" clear-text="Clear" close-text="Close" ng-readonly="false" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openDatePicker($event)"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
</form>
</div>
</body>
</html>
The problem is that when I try to open one datepicker, all of them are opened (logically, as they share the same $scope.opened variable). Also when I close them and try to open them again, nothing happens.
Is there a elegant way to achieve this?
Thanks.
All of your datepickers have id="datePickerItem".
The id attribute must be unique in html. Try this instead:
id="datePickerItem_{{$index}}"
This will add the ng-repeat's current index to the id, so you can be relatively certain your id's are unique. This should also prevent all the datepickers from opening at the same time.
Also, you're using one and the same opened variable for all datepickers.
Try this instead:
<div ng-repeat="item in details" class="input-group">
<input ng-model="item.parameterValue" type="text" class="form-control"
id="datePickerItem_{{$index}}" datepicker-popup="shortDate"
is-open="opened[$index]" datepicker-options="dateOptions" current-text="Today"
clear-text="Clear" close-text="Close" ng-readonly="false" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openDatePicker($event, $index)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</div>
And:
$scope.opened = [];
$scope.openDatePicker = function($event, index) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened[index] = true;
};
Just make sure you set $scope.opened[index] to false, in case you close the datepicker.
try this:
$scope.open = function($event,opened) {
$event.preventDefault();
$event.stopPropagation();
$scope[opened] = true;
};
and in your html
ng-click="open($event, 'nameOfYourModel')"
why not bind opened on the repeat object?
like:
<div ng-repeat="item in details" class="input-group">
<input ng-model="item.parameterValue" type="text" class="form-control"
id="datePickerItem_{{$index}}" datepicker-popup="shortDate"
is-open="item['opened']" datepicker-options="dateOptions" current-text="Today"
clear-text="Clear" close-text="Close" ng-readonly="false" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openDatePicker($event, item)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
and in controller:
$scope.openDatePicker = function($event, item) {
$event.preventDefault();
$event.stopPropagation();
if(item.opened){
item.opened = !item.opened;
} else{
item.opened = true;
}
};

angular function gets spammed on load

I have the following controller:
app.controller('SignUpController', ['$http','$sessionStorage','api', '$scope','$state', '$log', 'Session','clientSocket', function ($http, $sessionStorage, api, $scope,$state, $log, Session, clientSocket) {
var signupCtrl = this;
signupCtrl.getRandomPerson = function () {
var isGuy = Math.floor((Math.random() * 2));
if(isGuy == 1 || isGuy == 0){
var picture = Math.floor((Math.random()*9));
return 'img/guys/guy-'+picture+'.jpg';
}else{
var picture = Math.floor((Math.random()*10));
return 'img/guys/woman-'+picture+'.jpg';
}
}
}]);
With the following html:
<div class="container w-xxl w-auto-xs" ng-controller="SignUpController as signUpCtrl" ng-init="app.settings.container = false;">
<div class="m-b-lg">
<div class="bg-white p-md">
<div class="block m-t text-center m-b-xl">
<img src="{{signUpCtrl.getRandomPerson()}}" alt="Company Logo" class="img-circle" style="display: inline-block">
</div>
<form name="form" class="form-validation">
<div class="list-group list-group-sm">
<div class="list-group-item">
<input placeholder="Name" class="form-control no-border" ng-model="user.name" required>
</div>
<div class="list-group-item">
<input type="email" placeholder="Email" class="form-control no-border" ng-model="user.email" required>
</div>
<div class="list-group-item">
<input type="password" placeholder="Password" class="form-control no-border" ng-model="user.password" required>
</div>
</div>
<div class="checkbox m-b-md m-t-none">
<label class="i-checks">
<input type="checkbox" ng-model="agree" required><i></i> Agree the <a href>terms and policy</a>
</label>
</div>
<button type="submit" class="btn btn-lg btn-primary btn-block" ng-click="signup()" ng-disabled='form.$invalid'>Sign up</button>
<div class="line line-dashed"></div>
<p class="text-center"><small>Already have an account?</small></p>
<a ui-sref="access.signin" class="btn btn-lg btn-default btn-block">Sign in</a>
</form>
</div>
</div>
<div class="text-center" ng-include="'tpl/blocks/page_footer.html'">
{% include 'blocks/page_footer.html' %}
</div>
When i am loading this page the function getRandomPerson gets fired over 10 times. Sometimes so much that angular throws the following execption:
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"fn: expressionInputWatch","newVal":"img/guys/guy-2.jpg","oldVal":"img/guys/guy-1.jpg"}],[{"msg":"fn: expressionInputWatch","newVal":"img/guys/guy-6.jpg","oldVal":"img/guys/guy-2.jpg"}],[{"msg":"fn: expressionInputWatch","newVal":"img/guys/guy-1.jpg","oldVal":"img/guys/guy-6.jpg"}],[{"msg":"fn: expressionInputWatch","newVal":"img/guys/guy-4.jpg","oldVal":"img/guys/guy-1.jpg"}],[{"msg":"fn: expressionInputWatch","newVal":"img/guys/guy-8.jpg","oldVal":"img/guys/guy-4.jpg"}]]
http://errors.angularjs.org/1.3.14/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22m…guys%2Fguy-8.jpg%22%2C%22oldVal%22%3A%22img%2Fguys%2Fguy-4.jpg%22%7D%5D%5D
at REGEX_STRING_REGEXP (angular.js:63)
at Scope.$get.Scope.$digest (angular.js:14281)
at Scope.$get.Scope.$apply (angular.js:14506)
at done (angular.js:9659)
at completeRequest (angular.js:9849)
at XMLHttpRequest.requestLoaded (angular.js:9790)
Can anyone tell me whats going on?
The issue is that many digests might run on a particular scope within the page...even just to render once
Because every digest is seeing a new value from your function, it forces another digest. Thus you are creating an infinte loop
Just assign a scope variable randomImage and get that value returned from function, instead of placing function in the html
And as pointed out use ng-src so that final src gets set with a proper value after it is compiled. Otherwise you will have strange invalid path requests made to server
// will only run once when controller initializes
signupCtrl.randomImage = getRandomPerson();
// no need to be on scope since using it privately
var getRandomPerson = function() {
var isGuy = Math.floor((Math.random() * 2));
if(isGuy == 1 || isGuy == 0){
var picture = Math.floor((Math.random()*9));
return 'img/guys/guy-'+picture+'.jpg';
}else{
var picture = Math.floor((Math.random()*10));
return 'img/guys/woman-'+picture+'.jpg';
}
}
HTML
<!-- No src so browser won't make request to invalid path -->
<img ng-src="{{signUpCtrl.randomImage }}">
You have a src binding to your function, if you intend to do this you should be using ng-src so it won't be compiled before it is ready to be consumed.

Categories