i am having hard time while appending elements to the ng-repeat elements. Here is the fiddle link
http://jsfiddle.net/ukgym9f9/4/
app.directive("addAgendaRow", function($compile){
return{
restrict: 'A',
link: function(scope, element,attrs,controller){
element.on("click", function() {
console.log("clicked on add row");
$compile(element.parent().parent().parent().append('<tr class="add-remove-row" title="title"><td><div class="has-placeholder" placeholder="Your text Goes Here" contenteditable="true"></div></td><td class="add-remove-row"> </td></tr>'))(scope);
});
}
}
});
When i click on '+', it will remove the existing rows and creates new row. How do i combat this issue ?
Thanks in advance..
There is no need to $compile this when the click event occurs. Just try .closest() to bubble up the DOM tree and append it e.g. to the <table>:
app.directive("addAgendaRow", function() {
return {
restrict: 'A',
link: function(scope, element, attrs, controller) {
element.on("click", function() {
element.closest("table").append('<tr class="add-remove-row" title="title"><td><div class="has-placeholder" placeholder="Your text Goes Here" contenteditable="true"></div></td><td class="add-remove-row"> </td></tr>');
});
}
}
});
Related
I am using Angular 1.5.1. I have a checkbox on my form. I do not care about the truth/false indicator of the checkbox being checked/unchecked and so I do not want ng-model on it. What I care for is:
when checkbox is unchecked, I delete a specific array from my model
when checkbox is checked, I add an empty array back to my model
So I have created a directive that provides me with this functionality, very simple:
.directive('cbOnChecked', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
element.on('click', function(event) {
if(element[0].checked)
scope.$apply(attr.cbOnChecked);
});
}
};
})
.directive('cbOnUnchecked', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
element.on('click', function(event) {
if(!element[0].checked)
scope.$apply(attr.cbOnUnchecked);
});
}
};
})
Now I can do something like:
<input type="checkbox" cb-on-checked="counter = counter + 1" cb-on-unchecked="counter = counter - 1"/>
Or
<input type="checkbox" cb-on-checked="deleteUserList()" cb-on-unchecked="users = []"/> No users<br/>
The problem with this is - the form within which the checkbox is won't get marked as $dirty if there is no ng-model on the checkbox. Is there any way around this?
Here is an example js-fiddle. Thanks.
If you really want to go with your own directives you can just require parent form controller and mark it $dirty manually:
.directive('cbOnChecked', function() {
return {
require: '^form',
restrict: 'A',
link: function(scope, element, attr, ngFormController) {
element.on('click', function(event) {
ngFormController.$setDirty();
if(element[0].checked)
scope.$apply(attr.cbOnChecked);
});
}
};
})
Please see relevant jsFiddle
Within my directive whenever I paste an item on the 'searchBar' or text box I am not getting the updated value of the element text.
Here is my directive:
app.directive('searchBar', function() {
return {
restrict: 'AE',
replace: true,
template: '<input type="text" ng-model="searchData" placeholder="Enter a search" id="searchbarid" />',
link: function(scope, elem, attrs) {
elem.on('paste', function(evt) {
alert(evt.target.value);
});
}
};
});
Wrap the event inside of a $timeout of 0 so that it evaluates in the next $digest after angular evaluates all of its watches.
elem.on('paste', function(evt) {
$timeout(function() {
alert(evt.target.value);
},0)
});
http://jsfiddle.net/36qp9ekL/530/
is it possible to get the clicked row (scope) of a element in ng-repeat without nowing the name?
For example: scope.person works, but when I change persons into another name I can't use my directive global.
I need the data to do a edit like this: http://vitalets.github.io/x-editable/
I will write a directive which changes the text into a input field. To save it I need the name of the field, "lastname" in the example and the ID from the row.
HTML:
<tr ng-repeat="person in persons | orderBy:lastname">
<td class="editable">{{person.lastname}}</td>
<td>{{person.surname}}</td>
</tr>
Directive:
app.directive('editable', [function () {
return {
restrict: 'C',
link: function (scope, elem, attrs) {
elem.bind('click', function(event) {
console.log(scope.person)
});
}
};
}])
You can use Angular's tracking ng-repeats by $index and pass it to your directive:
HTML:
<tr ng-repeat="person in persons | orderBy:lastname">
<td editable="$index" class="editable">{{person.lastname}}</td>
<td>{{person.surname}}</td>
</tr>
Directive:
app.directive('editable', [function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
elem.bind('click', function(event) {
console.log(attrs.Editable);
});
}
};
}])
You are already catching the current scope and it is working fine you just need to manipulate the data and apply scope.$apply();
app.directive('editable', [function () {
return {
restrict: 'C',
link: function (scope, elem, attrs) {
elem.bind('click', function(event) {
console.log(scope.person)
scope.person.surname="hello"
console.log(scope.person)
scope.$apply();
});
}
};
}])
In the first console output you can see the original clicked element and in second console you can see the maupilated data.
Now why apply is required:- It is required to run the digest cycle of angular to adapt the change happen outside the scope of angular js (bind is jquery event not angular's).
Plunker
Add a Scope to your directive so you can pass any Model to be edited.
And display the ID with the Attrs variable.
app.directive('editable', [function () {
return {
scope: {
model : '='
},
restrict: 'C',
link: function (scope, elem, attrs) {
elem.bind('click', function(event) {
alert(scope.model +" "+ attrs.id )
});
}
};}]);
the html:
<span class="editable" model="person.lastname" id="{{$index}}">{{person.lastname}}</span>
The Fiddle
Browse how works the custom directives in angular. You can pass like parameter the lastname through 'attrs' in your link. Something like this:
html code:
<my-first-directive lastname="{{person.lastname}}"></my-first-directive>
custom directive code:
link: function (scope, elem, attrs) {
elem.bind('click', function(event) {
console.log(attrs['lastname'])
});
}
This approach not is good in my opinion. But i hope it works you.
If you read about scopes in directives you will can try other approachs.
You can pass the same parameter to directive scope so.
In your directive:
return {
restrict: 'C',
scope: {
lastname: '=' // If you want know more about this, read about scopes in directives
}
link: function (scope, elem, attrs) {
elem.bind('click', function(event) {
console.log(scope.lastname) // now, scope.lastname is in your directive scope
});
}
};
Be careful whit names when you work with directives. If your variable is 'myVar', when you write the directive html code you need write:
<my-first-directive my-var="myVar"></my-first-directive>
For the same reason that you need write 'my-first-directive' when you name directive is 'myFirstDirective'.
Good luck!
I'm hoping this isn't a duplicate - plenty of similar questions about but I can't find an answer that works.
I have an Angular directive, thus:
app.directive('emailInput', function(){
return {
restrict: 'E',
templateUrl: 'template.html',
link: function(scope, elem, attrs, ctrl){
elem.bind('keyup', function(){
// TODO - what?
})
}
}
}
and in the template html:
<input type="email" required ng-model="emailAddress" />
Without knowing the name of the form, inside the link function, I want to know the value of the emailAddress.$valid property - how can I get this?
You can require the formController which would give you access to all of the inputs registered to the form
app.directive('emailInput', function(){
return {
require: '^form', // We look for it on a parent, since it will be defined somewhere higher on the DOM.
restrict: 'E',
templateUrl: 'template.html',
link: function(scope, elem, attrs, ctrl){
elem.bind('keyup', function(){
ctrl.emailAddress.$valid //check validity
})
}
}
}
Remember that Angular keeps track of input elements by name. So you have to give your input a name attribute
<input type="email" required ng-model="emailAddress" name="emailAddress" />
I would also recommend possibly just passing all of this through a directive attribute. You probably don't want to hard code the field names. So you could just have an attribute that takes the validity
inputIsValid='formName.emailAddress.$valid'
And evaluate (or $watch it) in your directive.
We can check validity more easily without knowing the name of input elements.
app.directive('emailInput', function(){
return {
require: '^form', // We look for it on a parent, since it will be defined somewhere higher on the DOM.
restrict: 'E',
templateUrl: 'template.html',
link: function(scope, elem, attrs, ctrl){
elem.bind('keyup', function(){
ctrl.$valid //check validity here
})
}
}
}
This is an old post but for the people who get here by googling, this is the cleanest way to check validity of an input in your directive without knowing its name, so you can use your directive on any input element.
You just need to require the ngModelcontroller:
app.directive('emailInput', function(){
return {
require: 'ngModel'
restrict: 'E',
templateUrl: 'template.html',
link: function(scope, elem, attrs, ngModelCtrl){
elem.bind('keyup', function(){
ngModelCtrl.$valid //check validity
})
}
}
}
See the AngularJS document for ngModel.NgModelController, $valid under the Properties section:
https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
Know it's an old thread but if someone runs into this problem this is how I solved it:
app.directive('emailInput', function(){
return {
restrict: 'E',
templateUrl: 'template.html',
controller:function($scope){
$scope.isInvalid = function(){
return $scope.myelem.data().$ngModelController.$invalid;
}
},
link: function(scope, elem, attrs){
$scope.myelem = $(elem).find("input");
}
}
}
Here is a directive that will set dirty to true even if nothing has been typed in.
By default $dirty is set if something is typed in and wouldn't show a required error message until the user submits. With this
function() {
return function (scope, element, attrs) {
$(element).blur(function () {
scope.$apply(function() {
var field = scope.$eval(attrs.makeDirty);
field.$dirty = true;
});
});
};
HTML:
<label class="fieldLabel" for="confirmEmail">Confirm Email*</label>
<input type="text" id="confirmEmail" name="confirmEmail" ng-model="confirmEmail" ng-pattern="{{Ctrl.Model.Email.EmailAddress}}" required make-dirty="form.confirmEmail">
<span class="error" ng-show="form.confirmEmail.$error.pattern && form.confirmEmail.$dirty">Emails must match</span>
<span class="error" ng-show="form.confirmEmail.$error.required && (form.$submitted || form.confirmEmail.$dirty)">Confirm your email</span>
That allows me to give feedback as the user is filling out or tabbing on the form.
Let me give you another way to do it, it can be useful in some cases
link: function (scope, element, attrs, formCtrl) {
scope.fileSizeError=false;
scope.$watch(function () {
return formCtrl.fileP.$error.maxSize;
},function(newValue) {
scope.fileSizeError=newValue;
});
}
In my case I was inside a directive that is used to upload a file so I needed to know the state of the var $error.maxSize in the template so I did in that way.
I created a very simple directive which displays a key/value pair. I would like to be able to automatically hide the element if the transcluded content is empty (either zero length or just whitespace).
I cannot figure out how to access the content that gets transcluded from within a directive.
app.directive('pair', function($compile) {
return {
replace: true,
restrict: 'E',
scope: {
label: '#'
},
transclude: true,
template: "<div><span>{{label}}</span><span ng-transclude></span></div>"
}
});
For example, I would like the following element to be displayed.
<pair label="My Label">Hi there</pair>
But the next two elements should be hidden because they don't contain any text content.
<pair label="My Label"></pair>
<pair label="My Label"><i></i></pair>
I am new to Angular so there may be a great way handle this sort of thing out of the box. Any help is appreciated.
Here's an approach using ng-show on the template and within compile transcludeFn checking if transcluded html has text length.
If no text length ng-show is set to hide
app.directive('pair', function($timeout) {
return {
replace: true,
restrict: 'E',
scope: {
label: '#'
},
transclude: true,
template: "<div ng-show='1'><span>{{label}} </span><span ng-transclude></span></div>",
compile: function(elem, attrs, transcludeFn) {
transcludeFn(elem, function(clone) {
/* clone is element containing html that will be transcludded*/
var show=clone.text().length?'1':'0'
attrs.ngShow=show;
});
}
}
});
Plunker demo
Maybe a bit late but you can also consider using the CSS Pseudo class :empty.
So, this will work (IE9+)
.trancluded-item:empty {
display: none;
}
The element will still be registered in the dom but will be empty and invisible.
The previously provided answers were helpful but didn't solve my situation perfectly, so I came up with a different solution by creating a separate directive.
Create an attribute-based directive (i.e. restrict: 'A') that simply checks to see if there is any text on all the element's child nodes.
function hideEmpty() {
return {
restrict: 'A',
link: function (scope, element, attr) {
let hasText = false;
// Only checks 1 level deep; can be optimized
element.children().forEach((child) => {
hasText = hasText || !!child.text().trim().length;
});
if (!hasText) {
element.attr('style', 'display: none;');
}
}
};
}
angular
.module('directives.hideEmpty', [])
.directive('hideEmpty', hideEmpty);
If you only want to check the main element:
link: function (scope, element, attr) {
if (!element.text().trim().length) {
element.attr('style', 'display: none;');
}
}
To solve my problem, all I needed was to check if there were any child nodes:
link: function (scope, element, attr) {
if (!element.children().length) {
element.attr('style', 'display: none;');
}
}
YMMV
If you don't want to use ng-show every time, you can create a directive to do it automatically:
.directive('hideEmpty', ['$timeout', function($timeout) {
return {
restrict: 'A',
link: {
post: function (scope, elem, attrs) {
$timeout(function() {
if (!elem.html().trim().length) {
elem.hide();
}
});
}
}
};
}]);
Then you can apply it on any element. In your case it would be:
<span hide-empty>{{label}}</span>
I am not terribly familiar with transclude so not sure if it helps or not.
but one way to check for empty contents inside the directive code is to use iElement.text() or iElement.context object and then hide it.
I did it like this, using controllerAs.
/* inside directive */
controllerAs: "my",
controller: function ($scope, $element, $attrs, $transclude) {
//whatever controller does
},
compile: function(elem, attrs, transcludeFn) {
var self = this;
transcludeFn(elem, function(clone) {
/* clone is element containing html that will be transcluded*/
var showTransclude = clone.text().trim().length ? true : false;
/* I set a property on my controller's prototype indicating whether or not to show the div that is ng-transclude in my template */
self.controller.prototype.showTransclude = showTransclude;
});
}
/* inside template */
<div ng-if="my.showTransclude" ng-transclude class="tilegroup-header-trans"></div>