Javascript AngularJs (NG1) If ng-model value is null - javascript

I am using AngularJs (Angular1) in a project and I have an ng-model which gets a value:
<input id="myinput" type="text" class="form-control" ng-model="ctrl.myDate" ng-required="true" />
This works fine as far as ctrl.myDate is not null be breaks the code when it's null
Is there a way where I can check if the value is null and add (for example) today's date if it's null, so it doesn't break?
How can I do this?

<input ng-if="ctrl.myDate" id="myinput" type="text" class="form-control" ng-
model="ctrl.myDate" ng-required="true" />
<!-- default date when myDate is null -->
<input ng-if="!ctrl.myDate" id="myinput" type="text" class="form-control" ng-
model="ctrl.defaultDate" ng-required="true" />
You can store a defaultDate in the $scope.ctrl.

1) Supposing that ctrl.myDate is null, then it is probably initialized somewhere in your controller. Based upon that, the right place to replace the model value is your controller and not the view.
So in this case your code might look something like this:
function setDate() {
const today = new Date();
vm.myDate = getDate() || today; // If date is null then assign today.
}
function getDate() { //This might be an http call that brings the date.
return null;
}
2) On the other hand if your model is just for presentation purpose you can do something like this using ng-value directive, but there is probably no reason to use input tag.
<input id="myinput" type="text" class="form-control" ng-value="ctrl.myDate || ctrl.today" ng-required="true" />
Here's a working sample based on your question.

Can you move the condition to where you controller is initialized rather than in the ng-model? e.g. ng-init?
var myApp = angular.module('myApp',[]);
myApp.controller('TestController', ['$scope', function($scope) {
var testController = this;
testController.init = function (dateInput) {
if (dateInput !== null) {
testController.myDate = dateInput !== null ? dateInput : getDate();
}
};
}]);
and
<div ng-controller="TestController as ctrl" ng-init="ctrl.init(yourDate)">
<input id="myinput" type="text" class="form-control" ng-model="ctrl.myDate" ng-required="true" />
</div>

Related

Cannot get value of ng-model through $scope

I am trying to get the value of the ng-model when clicking a button which triggers a function to add each ng-model value to an object. When trying to get the value of $scope.shipNameFirst, it comes up as undefined in the second example.
I've read that it's better to get the value of $scope on the view rather than passing it through the stripeBtn function, so ideally I'd like to do it that way. Hopefully this makes sense.
Can someone explain why this is not working?
Working
HTML
<input type="text" ng-model="shipNameFirst">
<input type="text" ng-model="shipNameLast">
<button type="button" ng-click="stripeBtn(shipNameFirst, shipNameLast)">Checkout with Stripe</button>
Controller
$scope.stripeBtn = function(shipNameFirst, shipNameLast){
$scope.details = {
recNameFirst: shipNameFirst,
recNameLast: shipNameLast,
}
}
Not Working
HTML
<input type="text" ng-model="shipNameFirst">
<input type="text" ng-model="shipNameLast">
<button type="button" ng-click="stripeBtn()">Checkout with Stripe</button>
Controller
$scope.stripeBtn = function(){
console.log($scope.shipNameFirst); //logging this (with $scope) comes up as undefined
$scope.details = {
recNameFirst: $scope.shipNameFirst,
recNameLast: $scope.shipNameLast,
}
}
Thanks!
Check the following code. It's working nicely.
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope){
$scope.stripeBtn = function(){
console.log($scope.shipNameFirst);
$scope.details = {
recNameFirst: $scope.shipNameFirst,
recNameLast: $scope.shipNameLast,
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<input type="text" ng-model="shipNameFirst">
<input type="text" ng-model="shipNameLast">
<button type="button" ng-click="stripeBtn()">Checkout with Stripe</button>
</div>

angularjs set default date input at today

I try to set the default value of an input field at today. I can do that with an text field but when I try with an date field it fails.
HTML code :
<div ng-controller="MyCtrl">
<form name="new">
<input type="date" ng-model="date_rdv" />
<input type="text" ng-model="form_text" />
</form>
</div>
JS code :
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, $filter) {
$scope.form_text = $filter('date')(Date.now(), 'yyyy-MM-dd');
$scope.date_Rdv = $filter('date')(Date.now(), 'yyyy-MM-dd');
}
Why it works with text field and not with date field ?
JSFiddle.
You are not referencing the correct property of $scope.
Either use:
$scope.date_rdv = $filter('date')(Date.now(), 'yyyy-MM-dd');
Or
<input type="date" ng-model="date_rdv" />.
I've updated your fiddle here:
http://jsfiddle.net/68j7y439/1/

Set ng-model value to button click

I have this little snippet of code to set the root.lowWeight and root.highWeight to my controller.
<input type="number" placeholder="Enter Low Range..." class="form-control input-xs">
<input type="number" placeholder="Enter High Range..." class="form-control input-xs">
<button class="btn btn-primary" ng-click="assignWeights()">Select Model</button>
Controller model:
//set the initial root scope to empty object
$scope.root = {};
//define root weight
$scope.root.lowWeight = 0;
$scope.root.highWeight = 0;
I know I could just use ng-model="root.lowWeight" to set the value, but ng-model triggers on element input event.
How can I either:
a) Send the input values in via assignWeights(param1, param2)
b) Change ng-model to trigger input on button click (seems hacky, less preferred solution)
I also know I could use JS/jQuery to trigger the input event and block the input event, but that's a last ditch effort I will 99.9% not do.
Solution using seperate scope object: plunkr
Html:
Low: <input type="text" name="lowRange" ng-model="inputData.lowWeight">
High: <input type="text" name="highRange" ng-model="inputData.highWeight">
Js:
$scope.assignWeights = function() {
$scope.lowWeight = $scope.inputData.lowWeight;
$scope.highWeight = $scope.inputData.highWeight
}
In your assignWeights function, you could use a selector to retrieve the values of the inputs and then assign your scope variable values based on that. Just assign a name to each input.
E.g.
<input type="number" placeholder="Enter Low Range..." class="form-control input-xs" name="lowRange">
<input type="number" placeholder="Enter High Range..." class="form-control input-xs" name="highRange">
<button class="btn btn-primary" ng-click="assignWeights()">Select Model</button>
Controller:
$scope.assignWeights = function() {
$scope.root.lowWeight = document.querySelector('input[name="lowRange"]').value
$scope.root.highWeight = document.querySelect('input[name="highRange"]').value
}
Plunker: http://plnkr.co/edit/lm8GFA0CD0zWwgAMSLah?p=preview

Angular: pass a default value from server side

I have on the server side (.NET Razor) a texbox that specified a default radius for a google map zoom that user can modify:
<input type="number" ng-model="radius">
But also for the first load, I should have a server-defined(and managed) variable
<input type="number" ng-model="defaultRadius"
style="display: none;" value="#myDefault">
Here is the code (JS FIDDLE)
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.$watch('defaultRadius', function(newValue) {
$scope.radius = newValue;
}, true);
}
<div ng-controller="MyCtrl">Hello, {{name}}!
<h2>Enter your radius (default {{defaultRadius}}): </h2>
<input type="number" ng-model="radius">
<input type="number" ng-model="defaultRadius"
style="display: none;" value="200">
</div>
However this does not seem to work... How to fix it?
in Angular way you should define the model in the controller, not in the view.
so you need to create a variable in your controller
$scope.defaultRadius = 200';
or there is another trick to do this use : ng-init="defaultRadius=200"
<input type="number" ng-model="defaultRadius" style="display: none;" ng-init="defaultRadius=200" >
Working Fiddle

How to change form input value dynamically in AngularJS [duplicate]

I'm trying to show some editable results to the users, so I show them through an input field. This is a basic example of what I'm doing:
<div class="form-group">
<label>First number</label>
<input type="text" ng-model="first" ng-required="true" class="form-control">
</div>
<div class="form-group">
<label>Second number</label>
<input type="text" ng-model="second" ng-required="true" class="form-control">
</div>
<div class="form-group">
<label>The sum is: {{first + second }}</label>
<input type="text" ng-model="result" ng-required="true" class="form-control">
</div>
In the result's div, I used a label to test if the result is being obtained correctly, and it is. But if I edit the first or second values, the input's result doesn't update.
This is the controller used (yeah, the form is in a modal):
var ModalInstanceCtrl = function ($scope, $modalInstance) {
$scope.result = $scope.first + $scope.second;
$scope.confirm = function () {
$modalInstance.close(result);
};
$scope.cancelNewBet = function () {
$modalInstance.dismiss('cancel');
};
};
I thought the value was supposed to get automatically updated once I define how it is obtained. But clearly it misses something to change the result through script...
Thanks in advance.
What do you want to happen when the user edits the results input? Do you want the data binding to break (I assume not and ignore this possibility)? Do you want one of the inputs to adjust to the proper value?
If you only want to display the output, do this, in your controller:
$scope.result = function() { return $scope.first + $scope.second; }
And in your view:
{{ result() }}
But if you want the user to be able to edit the result and (let's say) have second be assigned (result - first), then you'd want something like this in your view (by the way, note the type="number"):
<input type="number" ng-change="adjustResult()" ng-model="first">
<input type="number" ng-change="adjustResult()" ng-model="second">
<input type="number" ng-change="adjustInput()" ng-model="result">
And in your controller:
$scope.adjustResult = function() {
$scope.result = $scope.first + $scope.second;
};
$scope.adjustResult(); // initialize result
$scope.adjustInput = function() {
$scope.second = $scope.result - $scope.first;
}

Categories