I'm using angular 1.4.x.
I'm making a custom directive that checks weather a field is unique on the server (the field is called "jmbg"). I have the following code:
(function() {
angular
.module('app')
.directive('uniqueJmbg', uniqueJmbg);
uniqueJmbg.$inject = ['$q', '$http'];
function uniqueJmbg($q, $http) {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ngModelCtrl) {
ngModelCtrl.$asyncValidators.uniqueJmbg = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return $http.get('/server/users/' + value)
.then(function resolved() {
return $q.reject('exists');
}, function rejected() {
return true;
});
};
}
}
})();
I am using the directive in HTML in the following way:
<input class="form-control" type="text" id="jmbg" name="jmbg" ng-model="rad.radnik.jmbg" ng-model-options="{ updateOn: 'default blur', debounce: {'default':400, 'blur':0 } }" unique-jmbg/>
In case it matters, I'm using my controllers with the controllerAs syntax.
Now, what happens is that the file containing my uniqueJmbg definition never loads (I can't see it in the browser debugger). If I move my code to a component which does load the app stops working (and there are no errors in the console), so there is no way for me to debug this.
Any idea what might be so wrong I can't even access the code in the browser?
Add dependencies to the module
angular
.module('app', [])
.directive(...
And you need to return an object from the module, so the correction would be:
function uniqueJmbg($q, $http) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ngModelCtrl) {
...
}
};
}
Related
I am new to angular js and want to validate a field on blur.
As i am entering the value the directive is called and is validating the entered value. i want this to happen on -blur.
I have already user on-blur in the html for calling some other function.
Below is the directive :
app.directive("emailCheck", function(){
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue, $scope) {
var emailPattern = /\S+#\S+\.\S+/;
var isEmailValid = emailPattern .test(viewValue)
ctrl.$setValidity('emailFormat', isEmailValid);
return viewValue;
})
}
};
});
How do i check for on blur event here?
Thanks in advance.
you should bind blur event to directive. try like this:
link: function (scope, elm, attrs, ctrl) {
elm.bind('blur',function(){
})
}
var app = angular
.module('MyApp', [
])
.controller('Main', ['$scope', function ($scope) {
}])
.directive("emailCheck", function(){
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
elm.bind('blur',function(){
alert("test");
})
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="main-content" ng-app="MyApp" ng-controller="Main as myCtrl">
<div>
<input type="text" ng-model="email" email-check>
</div>
</div>
Conventionally, when you use ngModel in your directive, you do not decide what event to hook into. You subscribe to whatever event the ngModel is hooked up to. This is not just blur by default.
The user of your directive can use ngModelOptions with updateOn:blur`` to update only on blur, like:
<input
email-check
name="testEmail" ng-model="testEmail"
ng-model-options="{ updateOn: 'blur' }">
<!-- Note using "updateOn: 'blur'" NOT "updateOn: 'default blur'" -->
ngModelOptions Docs
You will have to handle blur event inside the directive and remove the same from html element to handle it in the below fashion:
app.directive("emailCheck", function(){
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
elm.on('blur', function() {
// #TODO you will have to put your code here to handle this event
});
}
};
});
Try this.
define(['app'],function(app){
app.directive('myDecimals', function() {
return {
restrict: 'A',
link: function(scope, elm, attrs) {
elm.bind('blur',function(){
elm.val(elm.val()*1);
});
}
};
});
});
I have the following code:
<div id='parent'>
<div id='child1'>
<my-select></my-select>
</div>
<div id='child2'>
<my-input></my-input>
</div>
</div>
I also have two directives which get some data from the data factory. I need the two directives to talk to each other such that when a value in select box is changed the input in changes accordingly.
Here's my two directives:
.directive("mySelect", function ($compile) {
return {
restrict: 'E',
scope:'=',
template: " <select id='mapselectdropdown'>\
<option value=map1>map1</option> \
<option value=map2>map2</option> \
</select>'",
link: function (scope, element, attrs) {
scope.selectValue = //dont konw how to get the value of the select
}
};
})
.directive("myInput", function($compile) {
return {
restrict: 'E',
controller: ['$scope', 'dataService', function ($scope, dataService) {
dataService.getLocalData().then(function (data) {
$scope.masterData = data.input;
});
}],
template: "<input id='someInput'></input>",
link: function (scope, element, attrs) {
//here I need to get the select value and assign it to the input
}
};
})
This would essentially do the onchange() function that you can add on selects. any ideas?
You could use $rootScope to broadcast a message that the other controller listens for:
// Broadcast with
$rootScope.$broadcast('inputChange', 'new value');
// Subscribe with
$rootScope.$on('inputChange', function(newValue) { /* do something */ });
Read Angular docs here
Maybe transclude the directives to get access to properties of outer scope where you define the shared variable ?
What does this transclude option do, exactly? transclude makes the contents of a directive with this option have access to the scope outside of the directive rather than inside.
-> https://docs.angularjs.org/guide/directive
After much research this is what worked...
I added the following:
.directive('onChange', function() {
return {
restrict: 'A',
scope:{'onChange':'=' },
link: function(scope, elm, attrs) {
scope.$watch('onChange', function(nVal) { elm.val(nVal); });
elm.bind('blur', function() {
var currentValue = elm.val();
if( scope.onChange !== currentValue ) {
scope.$apply(function() {
scope.onChange = currentValue;
});
}
});
}
};
})
Then on the element's link function I added:
link: function (scope, elm, attrs) {
scope.$watch('onChange', function (nVal) {
elm.val(nVal);
});
}
Last added the attribute that the values would get set to in the scope:
<select name="map-select2" on-change="mapId" >
I am trying to implement dynamically configurable fields. I will get validation rules ng-required, ng-hidden, ng-disabled etc attributes as json from the server and set them dynamically through a directive.
I have the following directive code. It displays select values doubled JsBin link is http://jsbin.com/jiququtibo/1/edit
var app = angular.module('myapp', []);
app.directive('inputConfig', function( $compile) {
return {
require: 'ngModel',
restrict: 'A',
scope: '=',
compile: function(tElem, tAttrs){
console.log("compile 2");
tElem.removeAttr('data-input-config');
tElem.removeAttr('input-config');
tElem.attr('ng-required',true);
return {
pre: function (scope, iElement, iAttrs){
console.log('pre');
},
post: function(scope, iElement, iAttrs){
console.log("post");
$compile(tElem)(scope);
}
}
}
};
});
How can I solve this issue? I should be able to add directive dynamically.
To solve your problem you need to remove the following line from your post function:
$compile(tElem)(scope);
It's not clear to me why you are compiling here so I'm not sure if there will be any unintended side effects from this.
I found a solution following code is working.You should first clone, remove directive, prepare dom and compile
app.directive('inputConfig', function( $compile) {
return {
require: '?ngModel',
restrict: 'A',
compile:function (t, tAttrs, transclude){
var tElement = t.clone() ;
tElement.removeAttr('input-config');
tElement.attr('ng-required',true);
t.attr('ng-required',true);
return function(scope){
// first prepare dom
t.replaceWith(tElement);
// than compile
$compile(tElement)(scope);
};
}
}
});
With HTML like this...
<div ng-app="myApp">
<div ng-controller="inControl">
I like to drink {{drink}}<br>
<input my-dir ng-model="drink"></input>
</div>
</div>
and javascript like this...
var app = angular.module('myApp', []);
app.controller('inControl', function($scope) {
$scope.drink = 'water';
});
app.directive('myDir', function(){
return {
restrict: 'A',
link: function($scope, element, attrs, ctrl) {
// why is this logging undefined?
console.log(ctrl);
}
};
});
Why can I not access the controller from within my directive? Why is my call to ctrl giving me undefined?
EDIT: add demo...
Fiddle available here: http://jsfiddle.net/billymoon/VE9dX/
see multiple controller can be attached with one app and simillarly multiple directive can be attached with one app, so if you wants to use one controller in one directive than you can set the controller property of directive to the name of the controller you wants yo attach with like in your case
app.directive('myDir', function(){
return {
restrict: 'A',
controller: 'inControl'
link: function($scope, element, attrs, ctrl) {
// why is this logging undefined?
console.log(ctrl);
}
};
});
Despite this working with require:ngModel, this still isn't the best approach as it ties the directive directly to the controller. If you want your directive to communicate with your controller, you could be setting and reading off the scope.
HTML:
<div ng-app="myApp">
<div ng-controller="inControl">
I like to drink {{drink}}<br />
<input my-dir="drink"></input>
</div>
</div>
JS:
var app = angular.module('myApp', []);
app.controller('inControl', function($scope) {
$scope.drink = 'asdfasdf';
});
app.directive('myDir', function(){
return {
restrict: 'A',
link: function(scope, element, attrs) {
console.log(scope[attrs.myDir]);
}
};
});
Alternatively you can use my-dir="{{drink}}" and read it as attrs.myDir.
http://jsfiddle.net/8UL6N/1/
Adding require: 'ngModel', fixed it for me - not sure if there is another way to specify it...
app.directive('myDir', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, element, attrs, ctrl) {
// why is this logging undefined?
console.log(ctrl);
}
};
});
I would like to create a custom input type similar to the way AngularJS implements "email", for example.
<input type="email" ng-model="user.email" />
What I would like to create is an input type like this:
<input type="path" ng-model="page.path" />
Any ideas on how this can be accomplished? So far, I've only been able to figure out how to implement custom directives where 'path' is the name of the tag, attribute or class.
For example, I can get this to work but it is inconsistent with the other form fields and I'd really like them to look the same.
<input type="text" ng-model="page.path" path />
app.directive('path', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) { ... }
};
});
You can create your own input type="path" by creating an input directive with custom logic if the type attribute is set to "path".
I've created a simple example that simply replaces \ with /. The directive looks like this:
module.directive('input', function() {
return {
restrict: 'E',
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
if (attr.type !== 'path') return;
// Override the input event and add custom 'path' logic
element.unbind('input');
element.bind('input', function () {
var path = this.value.replace(/\\/g, '/');
scope.$apply(function () {
ngModel.$setViewValue(path);
});
});
}
};
});
Example
Update: Changed on, off to bind, unbind to remove jQuery dependency. Example updated.
An alternative solution can be achieved by using the $parsers property of the ngModelController. This property represents a chain of parsers that are applied to the value of the input component before passing them to validation (and eventually assigning them to the model). With this, the solution can be written as:
module.directive('input', function() {
return {
restrict: 'E',
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
if (attr.type !== 'path') return;
ngModel.$parsers.push(function(v) {
return v.replace(/\\/g, '/');
});
}
};
});
Note that there is another property $formatters which is a pipeline of formatters that transform a model value into the value displayed in the input.
See here for the plunker.
Considering compile function is the first in line, would it not be better with:
module.directive('input', function() {
return {
restrict: 'E',
require: 'ngModel',
compile: function Compile(tElement, tAttrs) {
if (tAttrs.type !== 'path') return;
return function PostLink(scope, element, attr, ngModel) {
// Override the input event and add custom 'path' logic
element.unbind('input');
element.bind('input', function () {
var path = this.value.replace(/\\/g, '/');
scope.$apply(function () {
ngModel.$setViewValue(path);
});
});
}
}
};
});