How to access directive parameter in Angular JS? - angularjs

I'm pretty new to Angular and I have run into a slight problem. I have this simple datepicker directive which works
app.directive('datepicker', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel){
$(elem).datepicker({
onSelect: function(dateText){
scope.$apply(function(){
ngModel.$setViewValue(dateText);
});
}
});
}
}
});
And the html I use to call it is
<input datepicker data-ng-model="day.date" readonly/>
I would like to be able to change the onSelect function called by the datepicker – hopefully with something like this.
<input datepicker="myOnSelectMethod()" data-ng-model="day.date" readonly/>
Then the directive would look something like this
app.directive('datepicker', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel){
if(myOnSelectMethod is defined){ //how do I access myOnSelectMethod here?
$(elem).datepicker({
onSelect: myOnSelectMethod();
});
}
else{ //proceed as before
$(elem).datepicker({
onSelect: function(dateText){
scope.$apply(function(){
ngModel.$setViewValue(dateText);
});
}
});
}
}
}
});
So my question is: how do I access the new onSelect function I want to execute from my link function?
Looking through the docs and other SO questions this seems like it should be possible but I haven't been able to make it work. I've come up with an ugly workaround by using an ng-click to activate the datepicker on a given element, but I would like to learn how to make this work if possible. Thanks!

You can check this way:
if( attr["datepicker"] == "myOnSelectMethod" &&
typeof myOnSelectMethod === "function" ){
// ...
}
Or even:
if( typeof scope[attr["datepicker"]] === "function" ){ // Instead of `scope`
// ... // may be any other object,
} // `window` for example

Related

Using a var in this Angular Directive to setValidity

I cannot figure out how to use a variable for the following case.
In html I have the following in a loop:
<span ng-show='myForm." + ids[i] + ".$error.missingInfo'>Wrong!</span>";
The generated html is correct, meaning ids[i] makes the appropriate html, like this:
<span ng-show='myForm.foo.$error.missingInfo'>Wrong!</span>";
I have an input element that has uses a custom validation directive:
<input name="me-foo" id="foo-me" validateI />
In the directive, I want to set the validity of "myForm.foo.$error.missingInfo", so my directive:
app.directive('validateI', function(){
return{
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var id= attr.id;
var x= id.indexOf("-");
//theId will be 'foo'
var theId= id.substring(x+1);
if(viewValue.length > 0) {
//this does not work
scope.myForm.theId.$setValidity("missingInfo", true);
//as a test, I hard-coded this and it worked:
scope.myForm.foo.$setValidity("missingInfo", true);
}
}
}
else{
console.log("*** summary is empty");
}
});
}
}
});
Is there a way to use a variable in this case, or how else would I get the 'foo' error message when the element tied to this directive is not named 'foo'?
Simply use the following to make it work:
ctrl.$setValidity("missingInfo", true);
Instead of using dot notation, use this notation:
scope.myForm[id].$setValidity("missingInfo", false);

ngModelController $modelValue is empty on directive startup

I have an attribute directive that I use on an input=text tag like this:
<input type="text" ng-model="helo" my-directive />
On my directive I'm trying to use the ngModelController to save the initial value of my input, in this case the value of the ng-model associated with it.
The directive is like this:
app.directive('myDirective', function () {
return {
restrict: "A",
scope: {
},
require: "ngModel",
link: function (scope, elm, attr, ngModel) {
console.log("hi");
console.log(ngModel.$modelValue);
console.log(ngModel.$viewValue);
console.log(elm.val());
}
}
});
The problem is that ngModel.$modelValue is empty maybe because at the time the directive is initialized the ngModel wasn't yet updated with the correct value. So, how can I store on my directive the first value that is set on my input field?
How to correctly access ngModel.$modelValue so that it has the correct value?
I'll also appreciate an explanation on why this isn't working as I'm not clearly understanding this from reading the docs.
Plunkr full example: http://plnkr.co/edit/QgRieF
Use $watch in myDirective
app.directive('myDirective', function () {
return {
restrict: "A",
scope: {
},
require: "ngModel",
link: function (scope, elm, attr, ngModel) {
var unwatch = scope.$watch(function(){
return ngModel.$viewValue;
}, function(value){
if(value){
console.log("hi");
console.log(ngModel.$modelValue);
console.log(ngModel.$viewValue);
console.log(elm.val());
unwatch();
}
});
}
}
});
For Demo See This Link

Compile custom directives

I'm trying to add dynamically a custom validation directive inside other custom directive. It works fine for system angular directive like "required", but not work for custom validate directive.
I have directive 'controlInput' with input, on which i dynamically add directive 'testValidation' (in real application in dependance from data of control-input).
<control-input control-data='var1'></control-input>
Directives:
app.directive('controlInput', function ($compile) {
return {
restrict: 'E',
replace: true,
template: '<div><input type="text" ng-model="var1"></div>',
link: function (scope, elem, attrs) {
var input = elem.find('input');
input.attr('required', true);
input.attr('test-validation', true);
$compile(elem.contents())(scope);
}
};
});
app.directive('testValidation', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function (value) {
if (value) {
var valid = value.match(/^test$/);
ctrl.$setValidity('invalidTest', valid);
}
return valid ? value : undefined;
});
}
};
});
Full example http://plnkr.co/edit/FylMfTugHrotEMSQyTfT?p=preview
In this example I also add simple input to be sure 'testValidation' directive is working.
Thanks for any answers!
EDIT:
I suggest you fix your original program by changing the template in the controlInput directive to:
template: '<div><input type="text" testdir required ng-model="var1"></div>'
I don't see why not do it as mentioned above, but another way would be to replace the input with a new compiled one:
input.replaceWith($compile(elem.html())(scope));
NOTE:
Change
var valid = value.match(/^test$/);
To
var valid = /^test$/.test(value);
From MDN:
String.prototype.match()
Return value
array An Array containing the matched results or null if there were no
matches.
RegExp.prototype.test() returns what you need, a boolean value.

Calling function defined in attributes in AngularJS directive

I'm using a jQuery-ui datapicker and have defined a directive (credit: http://www.abequar.net/posts/jquery-ui-datepicker-with-angularjs) to instantiate it. I'd now like to add an html attribute that defines the function to call to determine whether a day should be selectable in the datepicker. How would I do this?
The js:
//Directive for showing the jquery-ui datepicker
myApp.directive('datepicker', function() {
return {
restrict: 'A',
require : 'ngModel',
link : function (scope, element, attrs, ngModelCtrl) {
$j(function(){
//Instantiate the datepicker
element.datepicker({
dateFormat:'dd/mm/yy',
beforeShowDay:function(date) {
//TODO Call function defined in attrs, passing the date object to it
theDefinedFunction(date)
},
onSelect:function (date) {
ngModelCtrl.$setViewValue(date);
scope.$apply();
}
});
});
}
}
});
The html:
<input type="text" datepicker show-days="myShowDaysFunction()" />
The myShowDaysFunction() would be defined in the controller.
(Edit) - Controller function:
$scope.myShowDaysFunction = function(date) {
console.log("I get called"); //Logs to the console
console.log(date); //Logs undefined to the console
}
Thanks.
You need to create an isolate scope on your directive and take the function as a scope variable.
myApp.directive('datepicker', function() {
return {
restrict: 'A',
require : 'ngModel',
scope: {
showDays: '&'
},
link : function (scope, element, attrs, ngModelCtrl) {
$j(function(){
//Instantiate the datepicker
element.datepicker({
dateFormat:'dd/mm/yy',
beforeShowDay:function(date) {
//TODO Call function defined in attrs, passing the date object to it
scope.showDays({date: date});
},
onSelect:function (date) {
ngModelCtrl.$setViewValue(date);
scope.$apply();
}
});
});
}
}
});
Markup
<input type="text" datepicker show-days="myShowDaysFunction(date)" />
Controller Function
$scope.myShowDaysFunction = function(date) {
alert(date);
}
Plunker Exmaple
http://plnkr.co/edit/kRc76icPUa9qTkPH4UKm?p=preview

How do I get my directive to only fire on onchange?

I've defined a directive like so:
angular.module('MyModule', [])
.directive('datePicker', function($filter) {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$formatters.unshift(function(modelValue) {
console.log('formatting',modelValue,scope,elem,attrs,ctrl);
return $filter('date')(modelValue, 'MM/dd/yyyy');
});
ctrl.$parsers.unshift(function(viewValue) {
console.log('parsing',viewValue);
var date = new Date(viewValue);
return isNaN(date) ? '' : date;
});
}
}
});
The parser seems to fire every time I type a key in my textbox though -- what exactly is the default event, is it keyup, or input? And how do I change it to only fire onchange? It really isn't necessary to fire anymore often than that.
Furthermore, I'm actually manipulating the content of this input using jQuery UI's datepicker. When clicking on the calendar it doesn't seem to trigger the appropriate event that causes the model to be updated/parser to be triggered. I think I can force an event to be fired but I need to know which one.
Trying to use scope.$apply() but that doesn't seem to help any:
.directive('datepicker', function($filter) {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
$(elem).datepicker({
onSelect: function(dateText, inst) {
console.log(dateText, inst);
scope.$apply();
}
});
ctrl.$formatters.unshift(function(modelValue) {
console.log('formatting',modelValue);
return $filter('date')(modelValue, attrs.datePicker || 'MM/dd/yyyy');
});
ctrl.$parsers.unshift(function(viewValue) {
console.log('parsing',viewValue);
return new Date(viewValue);
});
}
}
})
I don't think the solution given here works for me because (a) I want to use the datepicker attribute value for choosing a date format or other options, but more importantly, (b) it seems to be passing back a string to the model when I want an actual date object... so some form of parsing has to be done and applied to the ng-model.
Here I created a mo-change-proxy directive, It works with ng-model and it updates proxy variable only on change.
In this demo I have even included improved directive for date-input. Have a look.
Demo: http://plnkr.co/edit/DBs4jX9alyCZXt3LaLnF?p=preview
angModule.directive('moChangeProxy', function ($parse) {
return {
require:'^ngModel',
restrict:'A',
link:function (scope, elm, attrs, ctrl) {
var proxyExp = attrs.moChangeProxy;
var modelExp = attrs.ngModel;
scope.$watch(proxyExp, function (nVal) {
if (nVal != ctrl.$modelValue)
$parse(modelExp).assign(scope, nVal);
});
elm.bind('blur', function () {
var proxyVal = scope.$eval(proxyExp);
if(ctrl.$modelValue != proxyVal) {
scope.$apply(function(){
$parse(proxyExp).assign(scope, ctrl.$modelValue);
});
}
});
}
};
});

Resources