how to use custom directive to add other angularjs directive - angularjs

I am a angularjs newbie, and I must miss something simple.
What I am trying to do is to create tooltip by using angular ui. I create a customer directive, in which it will add 3 angular directives to the attribute of the element based on the placeholder value:
myApp.directive('ngTooltip', function () {
return{
restrict: 'A',
link: function (scope, element, attrs) {
attrs.$set('tooltip', attrs['placeholder']);
attrs.$set('tooltip-placement', 'bottom');
attrs.$set('tooltip-trigger', 'focus');
}
}
});
In my markup, I have
and it got rendered as expected:
<input name="test" placeholder="this is test" tooltip="this is test" tooltip-placement="bottom" tooltip-trigger="focuse" />
However, the tooltip does not work. If I directly apply the 3 tooltip attributes to the markup, the tooltip works.
Looks like the 3 directives added by the custom directive do not get evaluated by angularjs.
Any ideas?

You can't dynamically add directives without recompiling the element with $compile, which will cause an infinite loop unless you resort to some workaround. There is an easier way to take care of this: declare a directive template and AngularJS will handle the directives properly.
myApp.directive('ngTooltip', function () {
return{
restrict: 'A',
template: '<input tooltip tooltip-placement="bottom" tooltip-trigger="focus">',
replace: true,
link: function (scope, element, attrs) {
attrs.$set('tooltip', attrs['placeholder']);
}
}
});
Working example: plunker.

Related

Angular form directive - how to set ng-model attribute to a value passed in through scope

I've got this form section (simplified for question):
<label>firstitem brand: </label><input ng-model="ctrl.object.item_attributes[0].brand">
<label>firstitem model: </label><input ng-model="ctrl.object.item_attributes[0].name">
<label>seconditem brand: </label><input ng-model="ctrl.object.item_attributes[1].brand">
<label>seconditem model: </label><input ng-model="ctrl.object.item_attributes[1].name">
And I would really like to instead do something like this:
<form-directive item="ctrl.object.item_attributes[0]"></form-directive>
<form-directive item="ctrl.object.item_attributes[1]"></form-directive>
As an Angular newbie, I'm stumped as to how to set the ng-model through my directive. I've tried passing it in directly through scope, and through the directive's link function, but with no luck. Any ideas?'
EDIT:
I tried the following directive per Steff's advice:
function fixIt () {
return {
restrict: 'EA',
require: "ngModel",
link: function (scope, elem, attrs, ngModel) {
attrs.ngModel = scope.comp
// scope.com = object.item_attributes[i]
}
}
};
angular
.module('app')
.directive('fixIt', fixIt);
with my input formatted as such:
<input fix-it ng-model="">
And I get the following error: angular.self-7f8df3e….js?body=1:13921 Error: [ngModel:nonassign] Expression '' is non-assignable.
If I give ng-model an initial value in my input that error goes away but nothing I do inside the link function inside the fixIt directive sticks.
If you want to set ng-model through your directive, you can consider the following method:
Directive code
(function(angular) {
'use strict';
angular.module('your_module_name',[]).directive('your_directive_name', function() {
return {
restrict: "EA",
require: 'ngModel',
link: function (scope, elem, attrs, ngModel) {
// accessing the ng-model value by using attr.ngModel
}
};
});
})(window.angular);
Remember to include your directive:
var myApp = angular.module('myapp', [ 'your_module_name']);
HTML code
<input your-directive-name ng-model="">
I use this method for my sparkling directive and it works just fine.
For form validation and other input specific settings, you can take a look at this stackoverflow question: Angularjs: form validation and input directive
If there's any misunderstanding of your problem please let me know, and hope this helps you :).
EDIT:
I'm not sure why you left the ng-model empty and bind the $scope variable in your directive. Maybe trying
<div ng-repeat="item in ctrl.object.item_attributes">
<input fix-it ng-model="item">
</div>

Change Angular directive element attribute dynamically

I am trying to create a custom directive which extends the functionality of an existing element. I would like to detect if a certain attribute exists and if not then add it (e.g. ng-class).
I have tried to achieve this during pre-compilation but angular does not react to the addition of the new attribute.
I created a plunker with a simple example using ng-hide.
<input hide type="submit" value="Submit"/>
app.directive('hide', function() {
return {
restrict: 'A',
compile: function(){
return {
pre: function(scope, element, attributes, controller, transcludeFn){
attributes.$set("ng-hide", true);
},
post: function(scope, element, attributes, controller, transcludeFn){
}
}
},
};
});
If I add ng-hide="true" in the html then the submit button is hidden correctly. If I leave it to the directive then I can see that the DOM has the element set up correctly but the element is not hidden:
<input hide="" type="submit" value="Submit" ng-hide="true">
Any help appreciated!
You can do this in the linking function by
Setting the directive's priority high, so it runs before all others.
Set it to terminal, so others don't run after it.
Recompile the element after you make changes to it (such as adding attributes)
For example:
app.directive('hide', function($compile) {
return {
restrict: 'A',
priority: 10000,
terminal: true,
link: function(scope, element, attrs) {
attrs.$set('ngHide', true);
attrs.$set('hide', null);
$compile(element)(scope);
}
};
});
As can be seen on http://plnkr.co/edit/tHNvCxVn2wURO38UtI0n?p=preview

Angular Directive Passing Template Name in as an attribute

if I wanted to pass into angular an attribute which is a template name stored on the templateCache, would doing something like the following be a good approach?
app.directive('myPopup', function() {
var directive = {
link: link,
scope {
'template': '#'
}
template: $templateCache.get(template);
restrict: 'E'
};
return directive;
function link(scope, element, attrs) {
}
});
Or should it be done on the compile statement, I guess so for performace??
I'm looking to ultimately wrap a bootstrap popover and then be able to provided html content through a template attribute allowing me to reuse popovers by providing different templates.
Can anyone offer any suggestions for the best course of action?
Thanks

From inside a custom directive how to change text of another span element?

I have an <input> which holds my custom directive as an attribute and inside that attribute I give the ID of destination that will receive the text. At the moment I am doing the text change with jQuery but I would rather use the full Angular way...So it's kinda of a binding but from within a directive. To make it simple, I made a simple draft of my code:
HTML Code
<input type="text" name="input1" my-directive="message1" />
<span id="message1"></span>
JS Code
// Angular - custom Directive
directive('myDirective', function($log) {
return{
require: "ngModel",
link: function(scope, elm, attrs, ctrl) {
var receiverId = attrs.myDirective;
var whateverText = 'blabla';
$('#'+receiverId).text(whateverText);
}
};
});
Using the ID on my <span> element is probably not the best solution, but that is how I got it working with jQuery. It's probably better to remove the ID, but then how could I update the text in my span after all? And let's not forget that it's a Form and we can have multiple input and span elements. Also note that I do not want to use the controller to pass the text, it has to stay within the directive as I want to re-use it.
Please don't tell me that I shouldn't do it this way, I want to stick with this behavior.
If the <span> will always be the next sibling as per your example, just use elm.next() as it is supported in Angular's native jqLite, no need to wrap with jQuery, e.g.
directive('myDirective', function($log) {
return{
require: "ngModel",
link: function(scope, elm, attrs, ctrl) {
var receiverId = attrs.myDirective;
var whateverText = 'blabla';
elm.next().text(whateverText);
}
};
});

Illegal use of ngTransclude directive in the template

I have two directive
app.directive('panel1', function ($compile) {
return {
restrict: "E",
transclude: 'element',
compile: function (element, attr, linker) {
return function (scope, element, attr) {
var parent = element.parent();
linker(scope, function (clone) {
parent.prepend($compile( clone.children()[0])(scope));//cause error.
// parent.prepend(clone);// This line remove the error but i want to access the children in my real app.
});
};
}
}
});
app.directive('panel', function ($compile) {
return {
restrict: "E",
replace: true,
transclude: true,
template: "<div ng-transclude ></div>",
link: function (scope, elem, attrs) {
}
}
});
And this is my view :
<panel1>
<panel>
<input type="text" ng-model="firstName" />
</panel>
</panel1>
Error: [ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div class="ng-scope" ng-transclude="">
I know that panel1 is not a practical directive. But in my real application I encounter this issue too.
I see some explanation on http://docs.angularjs.org/error/ngTransclude:orphan. But I don't know why I have this error here and how to resolve it.
EDIT
I have created a jsfiddle page. Thank you in advance.
EDIT
In my real app panel1 does something like this:
<panel1>
<input type="text>
<input type="text>
<!--other elements or directive-->
</panel1>
result =>
<div>
<div class="x"><input type="text></div>
<div class="x"><input type="text></div>
<!--other elements or directive wrapped in div -->
</div>
The reason is when the DOM is finished loading, angular will traverse though the DOM and transform all directives into its template before calling the compile and link function.
It means that when you call $compile(clone.children()[0])(scope), the clone.children()[0] which is your <panel> in this case is already transformed by angular.
clone.children() already becomes:
<div ng-transclude="">fsafsafasdf</div>
(the panel element has been removed and replaced).
It's the same with you're compiling a normal div with ng-transclude. When you compile a normal div with ng-transclude, angular throws exception as it says in the docs:
This error often occurs when you have forgotten to set transclude:
true in some directive definition, and then used ngTransclude in the
directive's template.
DEMO (check console to see output)
Even when you set replace:false to retain your <panel>, sometimes you will see the transformed element like this:
<panel class="ng-scope"><div ng-transclude=""><div ng-transclude="" class="ng-scope"><div ng-transclude="" class="ng-scope">fsafsafasdf</div></div></div></panel>
which is also problematic because the ng-transclude is duplicated
DEMO
To avoid conflicting with angular compilation process, I recommend setting the inner html of <panel1> as template or templateUrl property
Your HTML:
<div data-ng-app="app">
<panel1>
</panel1>
</div>
Your JS:
app.directive('panel1', function ($compile) {
return {
restrict: "E",
template:"<panel><input type='text' ng-model='firstName'>{{firstName}}</panel>",
}
});
As you can see, this code is cleaner as we don't need to deal with transcluding the element manually.
DEMO
Updated with a solution to add elements dynamically without using template or templateUrl:
app.directive('panel1', function ($compile) {
return {
restrict: "E",
template:"<div></div>",
link : function(scope,element){
var html = "<panel><input type='text' ng-model='firstName'>{{firstName}}</panel>";
element.append(html);
$compile(element.contents())(scope);
}
}
});
DEMO
If you want to put it on html page, ensure do not compile it again:
DEMO
If you need to add a div per each children. Just use the out-of the box ng-transclude.
app.directive('panel1', function ($compile) {
return {
restrict: "E",
replace:true,
transclude: true,
template:"<div><div ng-transclude></div></div>" //you could adjust your template to add more nesting divs or remove
}
});
DEMO (you may need to adjust the template to your needs, remove div or add more divs)
Solution based on OP's updated question:
app.directive('panel1', function ($compile) {
return {
restrict: "E",
replace:true,
transclude: true,
template:"<div ng-transclude></div>",
link: function (scope, elem, attrs) {
elem.children().wrap("<div>"); //Don't need to use compile here.
//Just wrap the children in a div, you could adjust this logic to add class to div depending on your children
}
}
});
DEMO
You are doing a few things wrong in your code. I'll try to list them:
Firstly, since you are using angular 1.2.6 you should no longer use the transclude (your linker function) as a parameter to the compile function. This has been deprecated and should now be passed in as the 5th parameter to your link function:
compile: function (element, attr) {
return function (scope, element, attr, ctrl, linker) {
....};
This is not causing the particular problem you are seeing, but it's a good practice to stop using the deprecated syntax.
The real problem is in how you apply your transclude function in the panel1 directive:
parent.prepend($compile(clone.children()[0])(scope));
Before I go into what's wrong let's quickly review how transclude works.
Whenever a directive uses transclusion, the transcluded content is removed from the dom. But it's compiled contents are acessible through a function passed in as the 5th parameter of your link function (commonly referred to as the transclude function).
The key is that the content is compiled. This means you should not call $compile on the dom passed in to your transclude.
Furthermore, when you are trying to insert your transcluded DOM you are going to the parent and trying to add it there. Typically directives should limit their dom manipulation to their own element and below, and not try to modify parent dom. This can greatly confuse angular which traverses the DOM in order and hierarchically.
Judging from what your are trying to do, the easier way to accomplish it is to use transclude: true instead of transclude: 'element'. Let's explain the difference:
transclude: 'element' will remove the element itself from the DOM and give you back the whole element back when you call the transclude function.
transclude: true will just remove the children of the element from the dom, and give you the children back when you call your transclude.
Since it seems you care only about the children, you should use transclude true (instead of getting the children() from your clone). Then you can simply replace the element with it's children (therefore not going up and messing with the parent dom).
Finally, it is not good practice to override the transcluded function's scope unless you have good reason to do so (generally transcluded content should keep it's original scope). So I would avoid passing in the scope when you call your linker().
Your final simplified directive should look something like:
app.directive('panel1', function ($compile) {
return {
restrict: "E",
transclude: true,
link: function (scope, element, attr, ctrl, linker) {
linker(function (clone) {
element.replaceWith(clone);
});
}
}
});
Ignore what was said in the previous answer about replace: true and transclude: true. That is not how things work, and your panel directive is fine and should work as expected as long as you fix your panel1 directive.
Here is a js-fiddle of the corrections I made hopefully it works as you expect.
http://jsfiddle.net/77Spt/3/
EDIT:
It was asked if you can wrap the transcluded content in a div. The easiest way is to simply use a template like you do in your other directive (the id in the template is just so you can see it in the html, it serves no other purpose):
app.directive('panel1', function ($compile) {
return {
restrict: "E",
transclude: true,
replace: true,
template: "<div id='wrappingDiv' ng-transclude></div>"
}
});
Or if you want to use the transclude function (my personal preference):
app.directive('panel1', function ($compile) {
return {
restrict: "E",
transclude: true,
replace: true,
template: "<div id='wrappingDiv'></div>",
link: function (scope, element, attr, ctrl, linker) {
linker(function (clone) {
element.append(clone);
});
}
}
});
The reason I prefer this syntax is that ng-transclude is a simple and dumb directive that is easily confused. Although it's simple in this situation, manually adding the dom exactly where you want is the fail-safe way to do it.
Here's the fiddle for it:
http://jsfiddle.net/77Spt/6/
I got this because I had directiveChild nested in directiveParent as a result of transclude.
The trick was that directiveChild was accidentally using the same templateUrl as directiveParent.

Resources