I have a custom angular directive that I'm using to change the display of price on an item. It's stored as a yearly value and I need to toggle between allowing users to see/edit as yearly or as monthly. So my custom directive is working on my input boxes (not able to use it for a label, div, span, but that's another issue).
I'm able to see that when I toggle the attribute, it picks up the change, but the value in the input doesn't change and I assume it's because not re-rendering the element. Is there any way I can force that to happen?
Here's my directive
angular.module('common.directive').directive('priceMonthly', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
var perMonth = false;
attr.$observe('priceMonthly', function(isMonthly) {
perMonth = (isMonthly.toLowerCase() === "true");
console.log("per month is " + perMonth); //updating perMonth correctly at this point
//guessing I need to do something here or in the function that changes the value of the attribute
});
function fromView(value){
return perMonth ? value * 12 : value;
}
function toView(value){
return perMonth ? value / 12 : value;
}
ngModel.$parsers.push(fromView);
ngModel.$formatters.push(toView);
}
};
});
Here's where I'm using it.
<input type="text" price-monthly="{{monthlySqftView}}"
class="form-control no-animate" name="item.priceLow"
ng-model="item.priceLow" ui-money-mask="2"/>
Here's a jsfiddle of where I'm currently at. So if the dropdown is on monthly, and I type in say 12, the price is correctly 144 which would be the full year price. Now if you change the dropdown to yearly, I need the input to update to 144.
https://jsfiddle.net/6tnbonzy/
Try scope.$apply() after you made required changes
#rschlachter, i am not sure if this can help you. AngularJS uses scope.digest() to clean the dirty data. you might need to put this line of code into your method
attr.$observe('priceMonthly', function(isMonthly) {
perMonth = (isMonthly.toLowerCase() === "true");
console.log("per month is " + perMonth); //updating perMonth correctly at this point
//guessing I need to do something here or in the function that changes the value of the attribute
//put it here, if you instantiated scope already.
scope.digest();
//scope.apply();
});
hope it works
It seems you want to do something like this jsfiddle?
<form name="ExampleForm">
<select ng-model="period">
<option value="monthly">monthly</option>
<option value="yearly">yearly</option>
</select>
<pre>
period = {{period}}
</pre>
Edit as {{period}}: <input price-monthly="obj.price" period="period" ng-model="obj.price" >
<pre>
price = {{obj.price}}
</pre>
</form>
And JS controller
.controller('ExampleController', function($scope) {
$scope.period = 'monthly';})
And JS directive
.directive('priceMonthly', function() {
return {
restrict: 'A',
scope:{
priceMonthly:"=",
period:"="
},
link: function(scope) {
scope.$watch('period',function(newval){
if(newval=='monthly')
scope.priceMonthly = scope.priceMonthly*12;
if(newval=='yearly')
scope.priceMonthly = scope.priceMonthly/12;
})
}
};});
I hope this will help you.
Related
I'm trying to make a field on a form valid by using the $valid class. I have the below HTML and JS code but even though the JS seems to work by modifying code editors, it doesn't validate the HTML. It doesn't seem to make it so $valid does anything but become true if the field has any text in it.
<input name="user" ng-model="user" ng-controller="SearchController" placeholder="User ID" required><br>
<span style="color:red" ng-show="searchForm.user.$dirty && searchForm.user.$invalid">A valid user ID is required.</span>
and
var searchApp = angular.module('searchApp', []);
searchApp.controller('SearchController', ['$scope', function ($scope) {
var users = ['11', '22', '33', '44']
return {
require: 'ngModel',
link: function (scope, element, attr, mCtrl) {
function idValidation(value) {
if (users.includes(value)) {
mCtrl.$setValidity('charE', true);
} else {
mCtrl.$setValidity('charE', false);
}
return value;
}
mCtrl.$parsers.push(idValidation);
}
};
}]);
The JS logic seems to work, but the HTML is not working correctly.
So you have a few minor errors in your code's logic to make this function correctly.
What you are attempting to do is create a custom validator. Your directive is using a $parser function, which is intended to parse a model's value for display. What you really want to be doing is working with a $validators function.
So, you would want to do something along the following:
var searchApp = angular.module('searchApp', []);
searchApp.directive('validUser', ['$scope', function ($scope) {
var users = ['11', '22', '33', '44']
return {
require: 'ngModel',
link: function (scope, element, attr, mCtrl) {
mCtrl.$validators.charE = function (value) {
return users.includes(value)
}
}
};
}]);
What happens is anytime the ngModel changes, it will run the value through the validators and determine if they are valid or invalid and automatically set ng-invalid-{name} or ng-valid-{name} (in this example, ng-invalid-charE and ng-valid-charE).
You can than use ngMessages to define your errors and they will show and hide as appropriate based on the validity.
Your ngController should more likely be a directive that adds the validator and your controller to contain the entire Search functionality/form HTML and be above your input to define your scope. Changing it to a directive would mean you'd remove ngController from the input and add an attribute for valid-user (as I've updated the name).
I have a custom directive and want to use the validators from an input field used inside this directive template. Is there a way to extend ngModelCtrl validators with the input validators?
This is my directive:
angular.module('myModule')
.directive('myUrl', function() {
return {
restrict: 'A',
require: ['ngModel', '^form'],
replace: true,
templateUrl: '/components/url/my-url.html',
scope: {},
link: function(scope, element, attrs, ctrls) {
var ngModelCtrl = ctrls[0];
var formCtrl = ctrls[1];
scope.formField = ngModelCtrl;
// Scope data vars
scope.url = '';
// Watchers
scope.$watch('url', function(newValue) {
ngModelCtrl.$setViewValue(newValue);
});
// Validators
var inputValidators = formCtrl['my-url'].$validators;
ngModelCtrl.$validators = angular.copy(inputValidators);
// Custom render
ngModelCtrl.$render = customRender;
function customRender() {
scope.url = ngModelCtrl.$viewValue;
}
}
}
});
This is my view:
<div>
<label>My URL</label>\
<input type="url" name="my-url" placeholder="http://" ng-model="url">
<div ng-messages="formField.$error" ng-show="formField.$invalid">
<span ng-message="url">Invalid URL.</span>
</div>
</div>
Here's a fiddle with this problem: https://jsfiddle.net/bsmaniotto/gzLmy1op/
Thanks.
EDIT:
Just realized that the problem is not on binding the input[url] validators to my custom directive ngModelCtrl's validators. The input[url] element is being validated and when an invalid input is entered the $modelValue is not set, and therefore, for my custom directive it is as nothing is inputted.
input validation is pretty easy in angular if you're using a controller. you can add:
ui-event: {keyup: 'controller.validationFunctionName(whatever)'}
Just fill in 'whatever' with the text in your input field and every time a key is let go it will check your validation function
If you want it to display an error beneath it just create another div that has an ng-if= to the result of that keyup function
I am playing with AngularJS directive. I want to format the data which is going to be displayed. This is what I am doing:
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="data" type="text" test />
<input type="button" ng-click="change()" value="Change"> {{data}}
<br>Hello <span ng-bind="data" test></span>
</div>
JS:
angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.data = 'yellow';
$scope.change = function() {
$scope.data = 'black';
};
})
.directive('test', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
ngModel.$formatters.push(function(value) {
//formats the value for display when ng-model is changed
return 'brown';
});
ngModel.$parsers.push(function(value) {
//formats the value for ng-model when input value is changed
return 'green';
});
}
};
});
I am able to format the data for the model and display it for input text. But I am not able to format the data for the span which is bound to a model. span is showing the model as it is. I don't know why the span is showing the value of the model. I want to show the formatted value to the span as well. Here is the jsFiddle.
You can use ng-model for only input. If you want to change a text in a div,span,label or any other element without input you can use seperators . {}
When you create a variable in $scope you can show it in your html.
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="data" type="text" test />
<input type="button" ng-click="change()" value="Change"> {{data}}
<br>Hello <span test>{data}</span>
</div>
Fiddle
I think it is working perfectly fine only thing is you are not taking the right example here.
First of all please read below:
Formatters change how model values will appear in the view.
Parsers change how view values will be saved in the model.
and now replace the code below
ngModel.$formatters.push(function(value) {
//formats the value for display when ng-model is changed
return 'brown';
});
ngModel.$parsers.push(function(value) {
//formats the value for ng-model when input value is changed
return 'green';
});
with
ngModel.$formatters.push(function(value) {
//formats the value for display when ng-model is changed
return value.toLowerCase();
});
ngModel.$parsers.push(function(value) {
//formats the value for ng-model when input value is changed
return value.toUpperCase();
});
I hope this help!!
Here's a jsfiddle example of what I'm trying to accomplish.
I'm trying to build a US phone number input where the view displays as (333) 555-1212, but the model binds to the numeric integer 3335551212.
My intention is to add custom validators to NgModelController which is why I have require: ng-model; there are simpler solutions without the isolate scope and NgModelController, but I need both.
You'll see an immediate error in the console: Error: Multiple directives [ngModel, ngModel] asking for 'ngModel' controller on: <input ng-model="user.mobile numeric" name="telephone" type="tel"> -- thought I was using an isolate scope here...
Thank you for looking #mimir137 but I appear to have solved it:
http://jsfiddle.net/hr121r18/8/
The directive was using replace: true, which ends up with this structure:
<form ng-controller="FooCtrl" class="ng-scope">
<p>Enter US phone number</p>
<input ng-model="user.mobile numeric" name="telephone" type="tel">
</form>
Both the template and the markup called for ng-model which led to the symptomatic error in the problem description. Once I removed that, it leads to this markup (note the wrapper element phone-number):
<form ng-controller="FooCtrl" class="ng-valid ng-scope ng-dirty ng-valid-parse" abineguid="BC0D9644F7434BBF80094FF6ABDF4418">
<p>Enter US phone number</p>
<phone-number ng-model="user.mobile" class="ng-untouched ng-valid ng-isolate-scope ng-dirty ng-valid-parse">
<input ng-model="numeric" name="telephone" type="tel" class="ng-valid ng-dirty ng-touched">
</phone-number>
</form>
But removing this required changes to $render; the elem passed into the link function is now phone-number and so you need to dig to grab the input inside it and set the value on that:
ngModel.$render = function () {
elem.find('input').val($filter('phonenumber')(ngModel.$viewValue));
};
There were a few other issues. $render() also needed to be called from the watcher.
Final:
var app = angular.module('myApp', []);
// i want to bind user.mobile to the numeric version of the number, e.g. 3335551212, but
// display it in a formatted version of a us phone number (333) 555-1212
// i am trying to make the directive's scope.numeric to have two-way binding with the controller's
// $scope.user.mobile (using isolate scope, etc.).
app.controller('FooCtrl', function ($scope) {
$scope.user = {
mobile: 3335551212
};
});
app.directive('phoneNumber', ['$filter', function ($filter) {
return {
restrict: 'E',
template: '<input ng-model="numeric" name="telephone" type="tel">',
require: 'ngModel',
scope: {
numeric: '=ngModel'
},
link: function (scope, elem, attrs, ngModel) {
// update $viewValue on model change
scope.$watch('numeric', function () {
ngModel.$setViewValue(scope.numeric);
ngModel.$render();
});
// $modelValue convert to $viewValue as (999) 999-9999
ngModel.$formatters.push(function (modelValue) {
return $filter('phonenumber')(String(modelValue).replace(/[^0-9]+/, ''));
});
// $viewValue back to model
ngModel.$parsers.push(function (viewValue) {
var n = viewValue;
if (angular.isString(n)) {
n = parseInt(n.replace(/[^0-9]+/g, ''));
}
return n;
});
// render $viewValue through filter
ngModel.$render = function () {
elem.find('input').val($filter('phonenumber')(ngModel.$viewValue));
};
}
};
}]);
app.filter('phonenumber', function () {
return function (number) {
if (!number) {
return '';
}
number = String(number);
var formattedNumber = number;
var c = (number[0] === '1') ? '1 ' : '';
number = number[0] === '1' ? number.slice(1) : number;
var area = number.substring(0, 3),
exchange = number.substring(3, 6),
subscriber = number.substring(6, 10);
if (exchange) {
formattedNumber = (c + '(' + area + ') ' + exchange);
}
if (subscriber) {
formattedNumber += ('-' + subscriber);
}
return formattedNumber;
}
});
HTML
<form ng-controller="FooCtrl">
<p>Enter US phone number</p>
<phone-number ng-model='user.mobile'></phone-number>
</form>
I created this fiddle that gets rid of most of your errors coming up in the console. Hopefully this will at least be able to put you on the right track.
I changed the template so that you can see that the filter is actually working.
It now has the typical {{ngModel | FilterName}} in plain text underneath the textbox.
The only real issue is displaying it in the textbox. I'm sure you will have no problem with that. I will check in the morning just in case you still have questions regarding this.
Edit: Alright it appears you have solved it already. Great job!
I Created js fiddle: Fiddle
I create a form with some ng-options in it, and it have strange behavior when you use the button instead of mouse (just click on the textbox and press "tab" and you can select it using arrow key).
<form ng-controller="MyApp" id="Apps" name="Apps" ng-submit="SendApp()" role="form" novalidate>
<input type="text" name="title" ng-model="Info.Title" />
<select id="Formula" ng-model ="Info.Genre" ng-change= "ChangeGenre()"
ng-options="id as name for (id, name) in Genre" blank></select>
<select class="form-control" ng-model ="Info.Program"
ng-options="Program as Name for (Program, Name) in Program" ng-change="ChangeProgram()" blank></select>
<h3>{{Info.Genre}}</h3>
<h3>{{Info.Program}}</h3>
<button type=submit>Submit this </button>
</form>
Javascript:
var theApp = angular.module("TheApp", []);
theApp.controller("MyApp", ['$scope', function($scope){
$scope.Program = {"1":"Music","2":"Theater","3":"Comedy"};
$scope.Genre = {"1":"Mystery", "2":"Thriller", "3":"Romance"};
$scope.ChangeProgram = function(){
alert($scope.Info.Program + " " + $scope.Info.Genre);
}
$scope.ChangeGenre = function (){
console.log($scope.Info.Genre);
}
$scope.SendApp = function(){
alert($scope.Info.Program + " " + $scope.Info.Genre);
}
}]);
The ng-model are not updated when you select the first options on First try.
What's Wrong, and How To Fix this?
Update:
As Mentioned on comment below, To reproduce, enter mouse into textfield, tab to combobox and try to select the second option (Thriller) using keyboard. This will fail on the first attempt, once the third or first option is selected, the second option is also recognized.
Using the the directive proposed here, this works for me:
theApp.directive("select", function() {
return {
restrict: "E",
require: "?ngModel",
scope: false,
link: function (scope, element, attrs, ngModel) {
if (!ngModel) {
return;
}
element.bind("keyup", function() {
element.triggerHandler("change");
})
}
}
})
I forked the fiddle.