Angular JS doesn't update select and input from date calendar - javascript

I'm using Angular JS and Bootstrap and I want to update the input of a datepicker calendar and a select from a function.
The values are updated but I can't see these on their correspondent inputs.
We can say that I'm updating the model but not the view. If I update the model from the view everything works fine but not to the contrary.
In the same form, if I update a a checkBox making clic ... Surprise. The select and the datepicker calendar are updated.
How can I update the view from my model and see this update?
Edit 1:
HTML
<select ng-model = "searchPAI.sistemaSelected" class="form-control" ng-options="sistema.nombreSistema for sistema in listSistemas">
</select>
<p class = "input-group" ng-controller = "dpFechaDesde">
<input type = "text" class = "form-control" uib-datepicker-popup = "{{format}}" name = "dtInicio" ng-model = "dateFrom" is-open = "popup1.opened" ng-change = "change2()"
min-date = "minDate" max-date = "maxDate" datepicker-options = "dateOptions" close-text = "Cerrar" clear-text = "Borrar" now-text = "Hoy" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
JS:
$scope.searchPAI.sistemaSelected = $scope.listSistemas[id];
$scope.$on("updateFechaDesde", function(){
$scope.dateFrom = publicDPFactory.date;
MyVar.data.dtFrom = publicDPFactory.date;
console.log("publicDPFactory.date: " + publicDPFactory.date);
console.log("scope.dateFrom: " + $scope.dateFrom);
});
I remember, everything works fine if I update the model from the view.
Edit 2:
More surprises! How I said previously, I update the value from the model and I can't see these on the view.
But, if I make a clic over "SI" ... Surprise!!! I can see the values updated on the view. You can see right now the select and the datapicker updated.

Fixed it!!!
To update the view from the model, after updated the model you have to call to ...
$scope.$apply();
And right now you can see all the changes!!!
How can you see, I don't need to make any clic over any other component from the form to see my values updated in the model on the view.

Related

Why does my bootstrap datepicker calendar not update when getting a value from a model?

When the view is first pulled up (using a new, empty model) the datepicker works great. When I pull values to my form from a model, the text in the input box looks fine, but when the calendar opens the date is completely wrong. How can this be fixed?
Controller
public IActionResult Daily(Daily? daily)
{
new ReportDaily().GetAvailableSavedCriteria(out List<ReportCriteria> reportCriteria, out Notification not);
if (daily.SelectedCriteria == null) {
//Create daily report object and initialize the default values
var newModel = new Daily
{
PaymentTypes = DGetPaymentTypes(),
Users = DGetUsers(),
Criteria = reportCriteria,
StartDate = DateTime.Today.Date,
EndDate = DateTime.Today.Date,
County = true,
Municipality = true
};
return View(newModel);
}
else
{
daily.PaymentTypes = HttpContext.Session.GetString("PaymentTypes") == null ? DGetPaymentTypes() : JsonConvert.DeserializeObject<List<Daily.PaymentType>>(HttpContext.Session.GetString("PaymentTypes"));
daily.Users = HttpContext.Session.GetString("Users") == null ? DGetUsers() : JsonConvert.DeserializeObject<List<Daily.User>>(HttpContext.Session.GetString("Users"));
daily.Criteria = reportCriteria;
return View("Daily", daily);
}
}
View
<div class="row col-12 formdatepicker">
<input asp-for="StartDate" type="text" class="form-control" id="startdatepicker" />
<span style="margin-left: 8px; margin-right: 8px; padding-top: 5px;">to</span>
<input asp-for="EndDate" type="text" class="form-control" id="enddatepicker" />
</div>
JavaScript
$("#startdatepicker").datepicker();
$("#enddatepicker").datepicker();
The value in the textbox is set to 03/10/2020 initially. After clicking in the textbox, the calendar is brought up with the selected date being the current day (in this case 03/25/2020) and when clicking out of the calendar without selecting the date, it gets set anyways. I would like the bootstrap datepicker calendar to be the same value as the textbox. Here is a GIF to illustrate the problem:
That's expected from Datepicker, to set default value to today.
If your script is on .cshtml page, you can simply do this:
$("#startdatepicker").datepicker("setDate", new Date('#Model.StartDate'));
$("#enddatepicker").datepicker("setDate", new Date('#Model.EndDate'));
If it's on a separated file, bind your dates to some data- fields or use <input value="#Model.StartDate" hidden="hidden" type="text"> then get them back by Jquery.

How to reset all Models on click event?

My requirement: Have to reset my select boxes on button click
Example :-
I have 3 select boxes. When I click on the select box some different data will come and after that the result will get published. I added a Remove button which resets only its parent select box. Now, what I want to know is,how to reset all the three select box on clicking the remove button.
sample code is as under :-
<button ng-click="removeObj(key,model1,0)">Remove</span></button>
controller code is as under :-
scope.removeObj = function(modelID, subModelID, selectBoxPos) {
modelID = 0;
subModelID = 0;
})
I want on click of removeObj function all modelID data get reset to zero.
Please help.
As I understand you do not need any parameters.. only create a meaningful name resetModels:
AngularJS Controller:
$scope.resetModels = function() {
// Set default value to your models...
$scope.modelID = 0;
$scope.subModelID = 0;
});
Html:
<button ng-click="resetScpeModels()">Remove</span></button>
If you want to reset all the values. You should use it like this
$scope.model = {};
$scope.model.modelID = 0;
$scope.model.subModelID = 0;
<input ng-model="model.modelID"/>
If you want to reset it. Call again
$scope.model = {};
Inside ng-click function.
When you give a name to your form it automatically gets added to the $scope.
In angular we are having a $setPristine() method on the $scope.formName. which should recursively take care of resetting your form.
You can reset a form by, $scope.formName.$setPristine(); but if you're binding a model object to your inputs, you need to take care of clearing those too, ie:
$scope.formModel={}; or angular.copy({}, formModel);
Working demo :
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.Reset = function(formModel) {
angular.copy({}, formModel);
$scope.formModel = {};
$scope.submitForm.$setPristine();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<form name="submitForm" ng-controller="myController">
<label for="first_field">First Model</label>
<input ng-model="formModel.firstModel" />
<br />
<label for="second_field">Second Model</label>
<input ng-model="formModel.secondModel" />
<br />
<button type="button" ng-click="Reset(formModel)">Reset</button>
</form>
</div>

All checkboxes getting checked even if one is checked

I'm making a basic todo app in angularjs.
Here's the code that's used to create a new todo with a checkbox
<div class="container" ng-controller = 'controller' >
<h3>Enter Todo </h3> <input type="text" ng-model = 'new'>
<button ng-click = 'add();' ng-disabled="status();">Add</button>
<div ng-repeat = "i in todo" >
<input type="checkbox" ng-model = "todo.done" /> <label>{{i.name}}</label>
</div>
</div>
The problem is that all the checkboxes get checked even when I check just one
Here's my controller module
todoApp.controller('controller',['$scope',function($scope){
$scope.new = '';
$scope.todo = [];
$scope.add = function(){
$scope.todo.push({name : $scope.new, done: false});
console.log($scope.todo);
$scope.new = '';
};
$scope.status = function(){
return !(/\S+/.test($scope.new));
};
ng-model = "i.done"
should solve the problem. In your version ng-model = "todo.done" todo is an array and angular just creates a property on the fly, when it's used for the first time. This way all of your checkboxes are connected to this property, that's why checking one checkbox affects all of them.
Because the list of the checkbox are sharing the same model. You can create a custom directive or you can use checklist-model directive.
Demo URL:
https://vitalets.github.io/checklist-model/

reset form value/object to empty upon ng-click in AngularJS

Description:
I'm using ui-router to load form pages upon icon click, whenever the user clicks the icon the new form should load ( remove any filled fields ). I have added ng-click on icon which can be leveraged to reset the form values.
index.html
<td>
<a ui-sref="form2"
title="yahoo">
<span class="glyphicon glyphicon-file" ng-click="newForm('new')" id="yahooIcon" ></span>
</a>
</td>
form2.html
<input type="text" name="firstname" ng-model="myModel.firstname"><br>
app.js
$scope.newForm = function (id){
if ( id == 'new' )
{
console.log(" model value inside: "+$scope.myModel.firstname);
$scope.myModel = {};
}
}
Problem:
ng-model data is showing undefined in controller and not able to reset the model upon clicking the icon.
The demo uses the same controller, However if my from has different controllers than index page. How can i send button click (ng-click) value to child controllers ?
DEMO ( Plunker )
Please Try This
//In Html Page
<button type="reset" ng-click="resetForm(formObject)">Clear Form</button>
//In Angular
$scope.resetForm = function(form) {
angular.copy({},form);
}

How to populate a different View on redirect and trigger button submit

I'm using MVC/ASP.NET
I have two views, one displays a list of items based on a group ID. the other page displays various pieces of information which is generated from multiple options. which options the user can enter are determined from a dropdown select.
View1.aspx
<input type="button"
value="View All Details%>"
class="button"
onclick="window.location = '<%:Url.Action("Index", "Report", new { id = Model.GroupID})%>'" />
I am able to successfully change to the indicated page and the page's controller get's called. Model.GroupID is the value I need to submit the new form with.
Q1: How can I trigger the dropdown box to go to the desired selected index and then populate the textbox with the value from `Model.GroupID'?
Index.aspx
...
<% using (Html.BeginForm("Report", "Report", FormMethod.Post, new { id = "some" }))
{
....
<%: Html.TextBoxFor(model => model.textBox.input, new { id = "textboxID", style = "width:" + Model.textBox.width + "px", maxlength = Model.textBox.maxLength })%>
<input type="submit" name="button" value="Find Details" style="width: 180px" />
}
I need to then submit the form, which will call my controller
Controller.cs
[Authorize]
[HttpPost]
public ActionResult Report([Bind(Include = "textBox")]Report values)
{
....
}
Q is there a way to call the directly from the different view? I don't mind creating a seperate method in the controller either to avoid binding....
for triggering a drop down list to select a specific item you can do like that:
#Html.DropDownListFor(model => model.GroupID, new SelectList((System.Collections.IEnumerable)ViewData["GroupsAvailable"], "Value", "Text", Model.GroupID))
but you must also pass the GroupsAvailable by ViewData or inside your model.
you can pass it like that by ViewData
IEnumerable<SelectListItem> availableGroups = db.Groups
.Where(g => g.IsActive) // for example
.OrderByDescending(c => c.Id)
.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.GroupName
});
ViewData["GroupsAvailable"] = availableGroups.ToList();
but over all you question it's not clear what do you want to achieve to answer your second question.

Categories