How to reset input field and checkbox in angularjs - javascript

I have a form with single input and another two checkbox labeled with Yes and No.
I want to save the input value when i click yes [this is not the problem].
After clicking yes, input and checkbox should reset. How can i do that?
setting ng-model to null is not working for me.
var app = angular.module("app", ['ionic']);
app.controller("MainCtrl", function ($scope,$timeout,$state) {
$scope.selected='other';
$scope.refresh = function(selected,answer){
if(selected == 'yes'){
$timeout(function(){
$scope.$apply(function(){
$scope.uncheck = false;
})
},250);
}
}
});
<html>
<head>
<link rel="stylesheet" href="http://code.ionicframework.com/1.3.2/css/ionic.css" />
<script src="http://code.ionicframework.com/1.3.2/js/ionic.bundle.min.js"></script>
</head>
<body>
<div class="bar bar-header bar-assertive">
<h1 class="title">Example</h1>
</div>
<div ng-app="app" style="margin-top:64px;padding:20px;">
<div ng-controller="MainCtrl" class="has-header">
<label class="item item-input">
<textarea msd-elastic ng-model="answer.three" placeholder="Your answer"></textarea>
</label>
<div>
<ion-checkbox class="cs-checkbox" ng-model="selected" ng-true-value="'no'" ng-change="statethree(selected,answer)">No</ion-checkbox>
<ion-checkbox class="cs-checkbox" ng-disabled="!answer.three" ng-checked="uncheck" ng-model="selected" ng-true-value="'yes'" ng-change="refresh(selected,answer)">Yes</ion-checkbox>
</div>
</div>
</div>
</body>
</html>

Below is working code with checkboxes but generally in such case it'd be better to use radio buttons (but it would chnage your UI design)
var app = angular.module("app", ['ionic']);
app.controller("MainCtrl", function ($scope,$timeout,$state) {
$scope.selected='other';
$scope.refresh = function(selected,answer){
if($scope.selected){
$timeout(function() {
$scope.answer.three = '';
$scope.selected = '';
}, 250)
};
}
});
<html>
<head>
<link rel="stylesheet" href="http://code.ionicframework.com/1.3.2/css/ionic.css" />
<script src="http://code.ionicframework.com/1.3.2/js/ionic.bundle.min.js"></script>
</head>
<body>
<div class="bar bar-header bar-assertive">
<h1 class="title">Example</h1>
</div>
<div ng-app="app" style="margin-top:64px;padding:20px;">
<div ng-controller="MainCtrl" class="has-header">
<label class="item item-input">
<textarea msd-elastic ng-model="answer.three" placeholder="Your answer"></textarea>
</label>
<div>
<ion-checkbox class="cs-checkbox" ng-true-value="false" ng-model="selected">No</ion-checkbox>
<ion-checkbox class="cs-checkbox" ng-disabled="!answer.three" ng-model="selected" ng-change="refresh(selected,answer)">Yes</ion-checkbox>
</div>
</div>
</div>
</body>
</html>
Also please note that you shouldn't use $apply inside $timeout callback because $timeout already triggers angular digest cycle.

Related

How to use multiple ng-app and add new modal

Here is my todo.js file
//let example = angular.module("example", ["ngStorage"]);
example.controller("ExampleController", function($scope, $localStorage) {
$scope.save = function() {
let testObject = [
{
name:"aaa",
lastName:"bbb"
},
{
name:"ccc",
lastName:"ddd"
}
]
let myVal = $localStorage.myKey;
$localStorage.$reset();
if(!myVal){
console.log("okey");
$localStorage.myKey = testObject;
} else {
myVal.push({
name:"fff",
lastName:"ggg"
})
$localStorage.myKey = myVal;
}
$scope.datas = $localStorage.myKey;
}
$scope.load = function() {
console.log($localStorage.myKey)
}
});*/
var app = angular.module("modalFormApp", ['ui.bootstrap']);
app.controller("modalAccountFormController", function ($scope, $modal, $log) {
$scope.showForm = function () {
$scope.message = "Show Form Button Clicked";
console.log($scope.message);
var modalInstance = $modal.open({
templateUrl: 'modal.html',
controller: ModalInstanceCtrl,
scope: $scope,
resolve: {
userForm: function () {
return $scope.userForm;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
var ModalInstanceCtrl = function ($scope, $modalInstance, userForm) {
$scope.form = {}
$scope.submitForm = function () {
if ($scope.form.userForm.$valid) {
console.log('user form is in scope');
$modalInstance.close('closed');
} else {
console.log('userform is not in scope');
}
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
And here is my index.html file:
<html>
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="../node_modules/angular-1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.10/ngStorage.min.js"></script>
<script src="./todo.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.9.0.js"></script>
</head>
<body>
<!--<div ng-app="example">
<div ng-controller="ExampleController">
<button ng-click="save()">Save</button>
<button ng-click="load()">Load</button>
<br>
<input type='text' ng-model='searchText' placeholder="Search..." />
<ul>
<li ng-repeat="data in datas | filter:searchText">
{{data.name}}
</li>
</ul>
</div>
</div>-->
<div ng-app="modalFormApp">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<!-- PAGE HEADER -->
<div class="page-header">
<h1>AngularJS Form Validation</h1>
</div>
<div ng-controller="modalAccountFormController">
<div class="page-body">
<button class="btn btn-primary" ng-click="showForm()">Create Account</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Lastly here is my modal.html:
<div class="modal-header">
<h3>Create A New Account!</h3>
</div>
<form name="form.userForm" ng-submit="submitForm()" novalidate>
<div class="modal-body">
<!-- NAME -->
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="name" required>
<p ng-show="form.userForm.name.$invalid && !form.userForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<!-- USERNAME -->
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8" required>
<p ng-show="form.userForm.username.$error.minlength" class="help-block">Username is too short.</p>
<p ng-show="form.userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div>
<!-- EMAIL -->
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="email" required>
<p ng-show="form.userForm.email.$invalid && !form.userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-disabled="form.userForm.$invalid">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</form>
I'm trying to open a modal when i click the button. I made comment line the other part which i'm using but it works fine. The second part is for only the modal but it is not working. I even can not open the modal. If there is a basic way to do this can you share with me? I only need to open this modal. I can handle the rest of it.
From the Docs:
There are a few things to keep in mind when using ngApp:
only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.
For more information, see
AngularJS ng-app Directive API Reference

AngularJS date in ng-model value not pass to controller

when i click CheckAvailability button date value doesnot pass to controller
<div class='input-group date'>
<input ng-model="BookedFromDate" type="text" value=#DateTime.Now.ToString("dd/MM/yyyy") class="form-control BookedFDate" style="border-width: 0 0 2px 0;">
<span class="input-group-addon">
<i class="font-icon font-icon-calend"></i>
</span>
</div>
Anguler:
$scope.CheckAvailability = function () {
alert("Hello, " + $scope.BookedFromDate);
};
Forget ASP. In AngularJS input doesn't need a value. Simply populate the ng-model. You can do it in controller or with ng-init in HTML. To mask/filter the date, use $filter service. It's usually not used directly, so I suggest applying a filter in ng-init. AngularJS has a date filter for this purpose.
Here is an example:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.now = new Date();
$scope.CheckAvailability = function() {
console.log("Date:", $scope.BookedFromDate);
};
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div class='input-group date'>
<input ng-model="BookedFromDate"
type="text"
ng-init="BookedFromDate = (now | date : 'dd/MM/yyyy')"
class="form-control BookedFDate"
style="border-width: 0 0 2px 0;">
<span class="input-group-addon">
<i class="font-icon font-icon-calend"></i>
</span>
<button ng-click="CheckAvailability()">Click</button>
</div>
</div>
</body>
</html>
Alternatively change the type from text to date to completely ignore the filter and masking.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.BookedFromDate = new Date();
$scope.CheckAvailability = function() {
console.log("Date:", $scope.BookedFromDate);
};
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div class='input-group date'>
<input ng-model="BookedFromDate"
type="date"
class="form-control BookedFDate"
style="border-width: 0 0 2px 0;">
<span class="input-group-addon">
<i class="font-icon font-icon-calend"></i>
</span>
<button ng-click="CheckAvailability()">Click</button>
</div>
</div>
</body>
</html>
Hope this code helps, in angular, value tag is of less use as we are binding the values 2-way.
<body ng-app="app">
<div ng-controller="EditCtrl">
<input type="text" ng-model="item.title" />
<input type="date" ng-model="item.date" />
{{item.date}}
</div>
</body>

Adding HTML-code for every click with ng-click

I am struggling to understand how to implement an add-function that adds a bit of HTML-code each time I click on a plus-button. The user should be able to add how many questions he/she wants, which means each time you click the button, the new code should be added underneath the previous one. Also I want the input to be added to an array in vm.createdset.question. This is the code I want to add each time I click on a button:
<div class="form-group row question-margin">
<label for="description" class="col-md-2 col-form-label">Fråga 1</label>
<div class="col-md-10">
<textarea type="text" class="form-control" placeholder="Beskriv scenariot och frågan" name="createdset" id="createdset" ng-model="vm.createdset.question.text"></textarea>
</div>
</div>
The button-code:
<i class="fa fa-plus-circle fa-3x new" aria-hidden="true"></i>
You can do this using ng-repeat and an array. All HTML within the div containing the ng-repeat will be repeated for every item in your array.
If you want to keep track of the number of the question you could add newQuestion.id = questionList.length to $scope.addQuestion and instead of using {{$index + 1}} you'll use {{question.id}} instead.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.questionList = [];
$scope.addQuestion = function() {
var newQuestion = {};
newQuestion.content = "";
$scope.questionList.push(newQuestion);
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="addQuestion()">Add Question</button>
<hr />
<div ng-repeat="question in questionList track by $index">
<div class="form-group row question-margin">
<label for="description" class="col-md-2 col-form-label">Fråga {{$index + 1}}</label>
<div class="col-md-10">
<textarea type="text" class="form-control" placeholder="Beskriv scenariot och frågan" name="createdset" id="createdset" ng-model="question.content"></textarea>
</div>
</div>
<hr />
</div>
</div>
</body>
</html>
According to your comments, this should be what you're looking for in your particular case:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, adminService) {
var vm = this;
vm.questionList = [];
vm.addQuestion = function() {
var newQuestion = {};
newQuestion.content = "";
vm.questionList.push(newQuestion);
};
vm.save = function() {
adminService.create(vm.questionList);
};
});
app.service('adminService', function() {
var create = function(answers) {
//Handle your answers and send the result to your webserver.
console.log(answers);
}
return {
create: create
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl as controller">
<button ng-click="controller.addQuestion()">Add Question</button>
<hr />
<div ng-repeat="question in controller.questionList track by $index">
<div class="form-group row question-margin">
<label for="description" class="col-md-2 col-form-label">Fråga {{$index + 1}}</label>
<div class="col-md-10">
<textarea type="text" class="form-control" placeholder="Beskriv scenariot och frågan" name="createdset" id="createdset" ng-model="question.content"></textarea>
</div>
</div>
<hr />
</div>
<div>
<button ng-click="controller.save()">Save</button>
</div>
</div>
</body>
</html>

How to make button as input type file

I have a button. It should act as file upload on Button click.
<div id="Rectangle-541">
<md-icon md-svg-src="./assets/images/csv.svg" class="ic_cloud_download_black_24px"></md-icon>
<md-button class="Upload-CSV-from-mem">Upload .CSV From Memory</md-button>
</div>
Check out this
var jimApp = angular.module("mainApp", []);
jimApp.controller('mainCtrl', function($scope){
$scope.fileChanged = function(){
angular.element('#fileUplaod').trigger('click');
};
$scope.profilePictureSelected = function(data){
console.log(data.files[0]);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
<div id="Rectangle-541">
<md-icon md-svg-src="./assets/images/csv.svg" class="ic_cloud_download_black_24px"></md-icon>
<md-button class="Upload-CSV-from-mem" ng-click="fileChanged()">Upload .CSV From Memory</md-button>
</div>
<input type="file" style="display:none" id="fileUplaod" ng-model="myFile" name='file' onchange="angular.element(this).scope().profilePictureSelected(this)" />
</div>

Angular js not firing change event on an already checked checkbox

Please check out this fiddle here. I am getting this weird behaviour from angular on change event on an initially checked chekbox. I checked this using jquery as well. The jquery event fires properly whilst the angular event fires only when the checked is initially unchecked.
Here is my complete code btw:
<html ng-app="testing">
<head>
<title>Angular ng-change test</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<div class="row" ng-controller="ChgCtrl">
<div class="col-md-12">
<form>
<div class="form-group">
<span class="text-info">ng-change</span>
<input type="checkbox" ng-model="formElem.checkbox" ng-change="toggleChange(formElem.checkbox)" ng-checked="formElem.checkbox == 1"/>
</div>
</form>
</div>
<div class="col-md-12">
<div class="col-md-6">
<h3>JQuery change event:</h3>
<P id="jq-messages"></p>
</div>
<div class="col-md-6">
<h3>Angular change event:</h3>
<p>{{message_change}}</p>
</div>
<p class="text-danger">Please note the first click on checkbox.</p>
</div>
</div>
<script type="text/javascript">
var app = angular.module('testing', []);
app.controller('ChgCtrl', function ($scope) {
$scope.formElem = {
checkbox: 1
};
$scope.message_change = '';
$scope.toggleChange = function (data) {
$scope.message_change = data === true ? 'Checked' : 'Unchecked';
console.info(data === true ? 'Checked' : 'Unchecked');
};
});
$(function () {
$('input[type=checkbox]').on('change', function (e) {
$('#jq-messages').html($(this).is(':checked') ? 'Checked' : 'Unchecked');
console.log($(this).is(':checked'));
});
});
</script>
</body>
You can do this with pure angular - jQuery is not needed.
Remove your ng-change and ng-checked attributes and just use ng-model:
<input type="checkbox" ng-model="formElem.checkbox"/>
Then toggle your text with ng-show and the model:
<p ng-show="formElem.checkbox">checked!</p>
<p ng-show="!formElem.checkbox">not checked.</p>
Demo
Removed ng-checked attribute, changed type of $scope.formElem.checkbox, corrected if statement ($scope.formElem.checkbox ? 'Checked' : 'Unchecked')
var app = angular.module('testing', []);
app.controller('ChgCtrl', function ($scope) {
$scope.formElem = {
checkbox: true
};
$scope.message_change = '';
$scope.toggleChange = function (data) {
$scope.message_change = ($scope.formElem.checkbox ? 'Checked' : 'Unchecked');
console.info(data === true ? 'Checked' : 'Unchecked');
};
});
$(function () {
$('input[type=checkbox]').on('change', function (e) {
$('#jq-messages').html($(this).is(':checked') ? 'Checked' : 'Unchecked');
console.log($(this).is(':checked'));
});
});
<body ng-app="testing">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<div class="row" ng-controller="ChgCtrl">
<div class="col-md-12">
<form>
<div class="form-group">
<span class="text-info">ng-change</span>
<input type="checkbox" ng-model="formElem.checkbox" ng-change="toggleChange(formElem.checkbox)" />
</div>
</form>
</div>
<div class="col-md-12">
<div class="col-md-6">
<h3>JQuery change event:</h3>
<P id="jq-messages"></p>
</div>
<div class="col-md-6">
<h3>Angular change event:</h3>
<p>{{message_change}}</p>
</div>
<p class="text-danger">Please note the first click on checkbox.</p>
</div>
</div>
</body>
ng-change event handler, as the name implies, will fire on target value change, but you are just initializing values, not changing them
My suggestion is not to use Jquery and do it with all angularJS. Also in controller if you want to see change , use $scope.$watch.
Her is demo .

Categories

Resources