How do I make ng-model-options use dynamic variables? - javascript

I am having an issue where ng-model-options isn't reflecting the changes I need it to.
For example, in the snippet below if you enter 4:00 pm into both time inputs you'll see the UTC output is different - the first is 6 and the second is 8. This is expected. However, the issue occurs when I select +0800 using the dropdown. Since this updates the timezone variable, both time inputs should now display 8 when I enter 4:00 pm since the first input should now use the timezone variable (as specified in its ng-model-options). However this isn't happening. Even after I clear the input and re-enter the time manually it still shows the incorrect time. How can I make the timezone option in ng-model-options use a dynamically changing variable such as timezone?
See issue below:
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.timezones = ['+1000', '+0800'];
$scope.timezone = $scope.timezones[0];
$scope.time = '';
$scope.eightTime = '';
});
angular.element(document).ready(() => {
angular.bootstrap(document, ['myApp']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-controller="myController">
<select ng-model="timezone">
<option ng-repeat="timezone in timezones" ng-value="timezone">{{timezone}}</option>
</select>
<p>Selected Timezone: {{timezone}}</p>
<input type="time" ng-model="time" ng-model-options='{timezone: timezone}' />
<p>Using dropdown T.Z of '{{timezone}}': {{time.getUTCHours()}}</p>
<input type="time" ng-model="eightTime" ng-model-options="{timezone: '+0800'}">
<p>Hardcoded '+0800': {{eightTime.getUTCHours()}}</p>
<!-- ^^^ This should be the output when '+0800' is selected in the dropdown -->
</div>

As per the documentation -
The ngModelOptions expression is only evaluated once when the
directive is linked; it is not watched for changes. However, it is
possible to override the options on a single ngModel.NgModelController
instance with NgModelController#$overrideModelOptions()
I have changed some of the lines to make it work for you :)
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.timezones = ['+1000', '+0800'];
$scope.timezone = $scope.timezones[0];
$scope.time = '';
$scope.eightTime = '';
$scope.$watch('timezone',function(v){
$scope.time = '';
$scope.myForm.time.$overrideModelOptions({'timezone': $scope.timezone});
//this will update the options whenever the timezone will be changed.
})
});
angular.element(document).ready(() => {
angular.bootstrap(document, ['myApp']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-controller="myController">
<form name="myForm">
<select ng-model="timezone" ng-options="timezone for timezone in timezones">
</select> <!-- ng-options is the correct way to provide options to the select dropdown -->
<p>Selected Timezone: {{timezone}}</p>
<input type="time" name="time" ng-model="time" ng-model-options='{timezone: timezone}' />
<p>Using dropdown T.Z of '{{timezone}}': {{time.getUTCHours()}}</p>
<input type="time" ng-model="eightTime" ng-model-options="{timezone: '+0800'}">
<p>Hardcoded '+0800': {{eightTime.getUTCHours()}}</p>
<!-- ^^^ This should be the output when '+0800' is selected in the dropdown -->
</form>
</div>
You will find more details about $overrideModelOptions here - https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$overrideModelOptions
Edited:
You can achieve it by creating a separate directive.
**For versions >1.6.2 **
angular.module('myApp', ['kcd.directives'])
.controller('myController', function($scope) {
$scope.timezones = ['+1000', '+0800'];
$scope.timezone = $scope.timezones[0];
$scope.time = '';
$scope.eightTime = '';
});
angular.module('kcd.directives', []).directive('kcdRecompile', ['$parse', function($parse) {
'use strict';
return {
transclude: true,
link: function link(scope, $el, attrs, ctrls, transclude) {
var previousElements;
compile();
function compile() {
transclude(scope, function(clone, clonedScope) {
// transclude creates a clone containing all children elements;
// as we assign the current scope as first parameter, the clonedScope is the same
previousElements = clone;
$el.append(clone);
});
}
function recompile() {
if (previousElements) {
previousElements.remove();
previousElements = null;
$el.empty();
}
compile();
}
scope.$watch(attrs.kcdRecompile, function(_new, _old) {
var useBoolean = attrs.hasOwnProperty('useBoolean');
if ((useBoolean && (!_new || _new === 'false')) || (!useBoolean && (!_new || _new === _old))) {
return;
}
// reset kcdRecompile to false if we're using a boolean
if (useBoolean) {
$parse(attrs.kcdRecompile).assign(scope, false);
}
recompile();
}, typeof $parse(attrs.kcdRecompile)(scope) === 'object');
}
};
}]);
angular.element(document).ready(() => {
angular.bootstrap(document, ['myApp']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js"></script>
<div ng-controller="myController">
<div kcd-recompile="timezone">
<select ng-model="timezone" ng-options="timezone for timezone in timezones">
</select> <!-- ng-options is the correct way to provide options to the select dropdown -->
<p>Selected Timezone: {{timezone}}</p>
<input type="time" name="time" ng-model="time" ng-model-options="{timezone: timezone}"/>
<p>Using dropdown T.Z of '{{timezone}}': {{time.getUTCHours()}}</p>
<input type="time" ng-model="eightTime" ng-model-options="{timezone: '+0800'}">
<p>Hardcoded '+0800': {{eightTime.getUTCHours()}}</p>
<!-- ^^^ This should be the output when '+0800' is selected in the dropdown -->
</div>
</div>
Reference Post - Dynamically Setting ngModelOptions in Angular

Related

AngularJS currency filter on input field

I have the following input field
<input type="text" class="form-control pull-right" ng-model="ceremony.CeremonyFee | number:2">
it is showing up correctly but has been disabled. The error I am receiving is "[ngModel:nonassign] Expression 'ceremony.CeremonyFee | number:2' is non-assignable". I understand why it is in error, but do not know how to get this to work on an input field. Thanks.
input with ng-model is for inputting data, number filter is for displaying data. As filter values are not bindable, they are not compatible, as you can see. You have to decide what you want to do with that input.
Do you want it to be an input? User can input his own number and you only needs to validate? Use i.e. pattern attribute:
<input type="text" ng-model="ceremony.CeremonyFee" pattern="[0-9]+(.[0-9]{,2})?">
Do you want it to be an output? User does not need to input his own value? Do not use ng-model, use value instead:
<input type="text" value="{{ceremony.CeremonyFee | number:2}}" readonly>
UPDATE:
really I don't understand what you need, but, if you want just that users can insert only two digits you should use a simple html attributes, have a look on min, max, step...
Follows a pure js solution, but I don't suggest something like that!
angular.module('test', []).controller('TestCtrl', function($scope) {
var vm = $scope;
var testValue = 0;
Object.defineProperty(vm, 'testValue', {
get: function() { return testValue; },
set: function(val) {
val = Number(val);
if(angular.isNumber(val) && (val < 100 && val > 0)) {
console.log(val);
testValue = val;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<div ng-controller="TestCtrl">
<input style="display:block; width: 100%; padding: 1em .5em;" type="number" ng-model="testValue" />
</div>
</section>
the ng-model directive requires a viewmodel assignable (or bindable) property, so, you cannot add a pipe...
angular.module('test', [])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-init="testValue = 0">
<label ng-bind="testValue | currency"></label>
<input style="display:block;" ng-model="testValue" type="number"/>
</div>
As an error states you have got an 'non-assignable' expression in your ng-model attribute.
You should use only ceremony.CeremonyFee.
| is used on ng-repeat to indicate what expression should be used as filter.
If you want to have that <input> populated with initial data in your controller/link you should give it an initial value ex.
$scope.ceremony = {
CeremonyFee: 'My first ceremony'
}
And every time your <input> element data will be changed CeremonyFee will be updated as well.
I found and used the solution found on this page.
http://jsfiddle.net/k7Lq0rns/1/
'use strict';
angular.module('induction').$inject = ['$scope'];
angular.module('induction').directive('format',['$filter', function ($filter) {
  return {
require: '?ngModel',
link: function (scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.unshift(function (a) {
return $filter(attrs.format)(ctrl.$modelValue)
});
elem.bind('blur', function(event) {
var plainNumber = elem.val().replace(/[^\d|\-+|\.+]/g, '');
elem.val($filter(attrs.format)(plainNumber));
});
}
  };
}]);
relatively easy to apply it.

How to pass focus to a new field as soon as it appears (angular 1.4)?

In the following example a new field is added (by adding a blank row to $scope) when the last field loses focus if it is not empty. The problem is that the new field is not added to the DOM in time to receive focus.
Is there a way to detect when angular has finished appending new field to the DOM and then pass focus to it?
Please, no "timer" solutions; the time it takes to change DOM is unknown and I need this focus switch to happen as fast as possible. We can do better!
JSFiddle
HTML
<div ng-app='a' ng-controller='b'>
<input type="text" ng-repeat="row in rows" ng-model="row.word" ng-model-options="{'updateOn': 'blur'}">
</div>
JS
angular.module('a', []).controller('b', function ($scope) {
$scope.rows = [{'word': ''}];
$scope.$watch('rows', function (n, o) {
var last = $scope.rows[$scope.rows.length - 1];
last.word && $scope.rows.push({'word': ''});
}, true);
});
This is a View-concern and so should be dealt with by using directives.
One way to do so, is to create a directive that grabs the focus when it's linked:
.directive("focus", function(){
return {
link: function(scope, element){
element[0].focus();
}
}
});
and use it like so:
<input type="text"
ng-repeat="row in rows"
ng-model="row.word"
focus>
Demo
Use $timeout without specifying a number of milliseconds. It will, by default, run after the DOM loads, as mentioned in the answer to this question.
angular.module('a', []).controller('b', function($scope, $timeout) {
$scope.rows = [{
'word': ''
}];
$scope.addRow = function() {
$scope.rows.push({
'word': ''
});
$timeout(function() {
//DOM has finished rendering
var inputs = document.querySelectorAll('input[type="text"]');
inputs[inputs.length - 1].focus();
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='a' ng-controller='b'>
<div ng-repeat="row in rows">
<input type="text" ng-model="row.word" ng-model-options="{'updateOn': 'blur'}"><br>
</div>
<input type="button" ng-click="addRow()" value="Add Row">
</div>

Define default values in angularjs form, validation doesnt'work

I'm lost about define default values in my form : http://1ffa3ba638.url-de-test.ws/zombieReport/partials/popup.html
validation doesnt'work too...
/*********************************** SubmitCtrl ***********************************/
app.controller('SubmitCtrl', ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {
/* data pre-define : date & url for test */
$scope.myForm = {};
$scope.myForm.date = new Date();
$scope.myForm.url = "prout";
/* ng-show things */
$scope.successMailZR = false;
$scope.errorMailZR = false;
$scope.send = function() {
if ($scope.myForm.$valid) {
alert('ok');
}
};
}]);
What is the correct way for define default values ?
edit :
for url i do it like this :
<input type="text" class="form-control" name="url" placeholder="{{myForm.url}}" value="{{myForm.url}}" ng-model="myForm.url" readonly="readonly" />
it's not working
There is a conflict between a binding model $scope.myForm and the form name <form name="myForm".
Angular will assign the form's controller into the $scope as its name i.e. $scope.myForm and that override what you have initialized.
Change your form name or the binding variable to have a different name.
In HTML:
<input value="default">
Or using Angular's ng-model:
<div ng-controller="YourCtrl">
<input ng-model="value">
</div>
function YourCtrl($scope) {
$scope.value = 'default';
}

angular: Validate multiple dependent fields

Let's say I have the following (very simple) data structure:
$scope.accounts = [{
percent: 30,
name: "Checking"},
{ percent: 70,
name: "Savings"}];
Then I have the following structure as part of a form:
<div ng-repeat="account in accounts">
<input type="number" max="100" min="0" ng-model="account.percent" />
<input type="text" ng-model="account.name" />
</div>
Now, I want to validate that the percents sum to 100 for each set of accounts, but most of the examples I have seen of custom directives only deal with validating an individual value. What is an idiomatic way to create a directive that would validate multiple dependent fields at once? There are a fair amount of solutions for this in jquery, but I haven't been able to find a good source for Angular.
EDIT: I came up with the following custom directive ("share" is a synonym for the original code's "percent").
The share-validate directive takes a map of the form "{group: accounts, id: $index}" as its value.
app.directive('shareValidate', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
params = angular.copy(scope.$eval(attr.shareValidate));
params.group.splice(params.id, 1);
var sum = +viewValue;
angular.forEach(params.group, function(entity, index) {
sum += +(entity.share);
});
ctrl.$setValidity('share', sum === 100);
return viewValue;
});
}
};
});
This ALMOST works, but can't handle the case in which a field is invalidated, but a subsequent change in another field makes it valid again. For example:
Field 1: 61
Field 2: 52
If I take Field 2 down to 39, Field 2 will now be valid, but Field 1 is still invalid. Ideas?
Ok, the following works (again, "share" is "percent"):
app.directive('shareValidate', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
scope.$watch(attr.shareValidate, function(newArr, oldArr) {
var sum = 0;
angular.forEach(newArr, function(entity, i) {
sum += entity.share;
});
if (sum === 100) {
ctrl.$setValidity('share', true);
scope.path.offers.invalidShares = false;
}
else {
ctrl.$setValidity('share', false);
scope.path.offers.invalidShares = true;
}
}, true); //enable deep dirty checking
}
};
});
In the HTML, set the attribute as "share-validate", and the value to the set of objects you want to watch.
You can check angularui library (ui-utility part). It has ui-validate directive.
One way you can implement it then is
<input type="number" name="accountNo" ng-model="account.percent"
ui-validate="{overflow : 'checkOverflow($value,account)' }">
On the controller create the method checkOverflow that return true or false based on account calculation.
I have not tried this myself but want to share the idea. Read the samples present on the site too.
I have a case where I have a dynamic form where I can have a variable number of input fields on my form and I needed to limit the number of input controls that are being added.
I couldn't easily restrict the adding of these input fields since they were generated by a combination of other factors, so I needed to invalidate the form if the number of input fields exceeded the limit. I did this by creating a reference to the form in my controller ctrl.myForm, and then each time the input controls are dynamically generated (in my controller code), I would do the limit check and then set the validity on the form like this: ctrl.myForm.$setValidity("maxCount", false);
This worked well since the validation wasn't determined by a specific input field, but the overall count of my inputs. This same approach could work if you have validation that needs to be done that is determined by the combination of multiple fields.
For my sanity
HTML
<form ng-submit="applyDefaultDays()" name="daysForm" ng-controller="DaysCtrl">
<div class="form-group">
<label for="startDate">Start Date</label>
<div class="input-group">
<input id="startDate"
ng-change="runAllValidators()"
ng-model="startDate"
type="text"
class="form-control"
name="startDate"
placeholder="mm/dd/yyyy"
ng-required
/>
</div>
</div>
<div class="form-group">
<label for="eEndDate">End Date</label>
<div class="input-group">
<input id="endDate"
ng-change="runAllValidators()"
ng-model="endDate"
type="text"
class="form-control"
name="endDate"
placeholder="mm/dd/yyyy"
ng-required
/>
</div>
</div>
<div class="text-right">
<button ng-disabled="daysForm.$invalid" type="submit" class="btn btn-default">Apply Default Dates</button>
</div>
JS
'use strict';
angular.module('myModule')
.controller('DaysCtrl', function($scope, $timeout) {
$scope.initDate = new Date();
$scope.startDate = angular.copy($scope.initDate);
$scope.endDate = angular.copy($scope.startDate);
$scope.endDate.setTime($scope.endDate.getTime() + 6*24*60*60*1000);
$scope.$watch("daysForm", function(){
//fields are only populated after controller is initialized
$timeout(function(){
//not all viewalues are set yet for somereason, timeout needed
$scope.daysForm.startDate.$validators.checkAgainst = function(){
$scope.daysForm.startDate.$setDirty();
return (new Date($scope.daysForm.startDate.$viewValue)).getTime() <=
(new Date($scope.daysForm.endDate.$viewValue)).getTime();
};
$scope.daysForm.endDate.$validators.checkAgainst = function(){
$scope.daysForm.endDate.$setDirty();
return (new Date($scope.daysForm.startDate.$viewValue)).getTime() <=
(new Date($scope.daysForm.endDate.$viewValue)).getTime();
};
});
});
$scope.runAllValidators = function(){
//need to run all validators on change
$scope.daysForm.startDate.$validate();
$scope.daysForm.endDate.$validate();
};
$scope.applyDefaultDays = function(){
//do stuff
}
});
You can define a single directive that is only responsible for this check.
<form>
<div ng-repeat="account in accounts">
<input type="number" max="100" min="0" ng-model="account.percent" />
<input type="text" ng-model="account.name" />
</div>
<!-- HERE IT IS -->
<sum-up-to-hundred accounts="accounts"></sum-up-to-hundred>
</form>
And here's the simple directive's code.
app.directive('sumUpToHundred', function() {
return {
scope: {
accounts: '<'
},
require: {
formCtrl: '^form'
},
bindToController: true,
controllerAs: '$ctrl',
controller: function() {
var vm = this;
vm.$doCheck = function(changes) {
var sum = vm.accounts.map((a)=> a.percent).reduce((total, n)=> total + n);
if (sum !== 100) {
vm.formCtrl.$setValidity('sumuptohundred', false);
} else {
vm.formCtrl.$setValidity('sumuptohundred', true);
}
};
}
};
});
Here's a plunker.

Angular Radio Values in ng-repeat

I'm new to Angular and am trying to capture the selected radio value but the documentation is not clear when using ng-repeat. Any help would be greatly appreciated.
<div ng-repeat="item in ed">
<label for="{{item['code']}}">
<input ng-change="getPlanTypes()" ng-model="ed" type="radio" id="{{item['code']}}" name="effective_date" value="{{item['code']}}">
{{item['date']}} </label>
</div>
Here is the controller but I'm unsure of the right way to get the selected radio value?
rates.controller('getEffectiveDates',
function($scope, $http, $location, myService, localStorageService) {
myService.effective_dates().then(function(ed) {
$scope.ed = ed;
});
$scope.getPlanTypes = function() {
console.log($scope.ed['code']); //Futile attempt that returns undefined
localStorageService.add('code',$scope.ed['code']);
$location.path("/plan-types");
}
});
Do
ng-click="getPlanTypes(item.code)"
and in your controller, you can get the value
$scope.getPlanTypes = function (ed) {
console.log(ed);
}
http://jsfiddle.net/2LZpv/
The HTML
<div ng-app="myApp" ng-controller="getEffectiveDates">
<div ng-repeat="item in ed">
<label for="{{item['code']}}">
<input ng-click="getPlanTypes(item)" ng-model="ed" type="radio" id="{{item['code']}}" name="effective_date" value="{{item['code']}}"/>
{{item['date']}} </label>
</div>
</div>
The JS
angular.module("myApp",[]).controller('getEffectiveDates', ["$scope", function($scope) {
$scope.ed = [{code:'1',date:"test date 1"},{code:'2',date:"test date 2"}];
$scope.getPlanTypes = function(selectedItem) {
console.log(selectedItem["code"]); //Feeble attempt that returns undefined
}
}]);

Categories

Resources