I'm trying to combine AngularJS and D3 -- two awesome libraries. This example is contrived but I have a legitimate use case where I'd like to insert HTML with AngularJS directives by means of D3.
Here's an example with:
a simple AngularJS directive,
a simple adding of content with D3
and finally adding a content with AngularJS directive using D3.
The last one does not work; why?
Here's the Fiddle.
HTML:
<body ng-app="d3">
<div hello></div>
<div hello-d3></div>
<div hello-d3-angular></div>
</body>
JS:
angular.module('d3', [])
.directive('hello', function() {
return {
template: 'Hello Angular!'
};
})
.directive('helloD3', function() {
return {
link: function(scope,elt) {
d3.select(elt[0]).append('div').text('Hello d3!')
}
};
})
.directive('helloD3Angular', function($compile) {
return {
link: function(scope,elt) {
var node = $compile('<div hello></div>')(scope);
d3.select(elt[0]).append(node[0]);
}
};
});
I think it's about D3 API, selection.append(name) .
The name may be specified either as a constant string or as a function that returns the DOM element to append.
http://jsfiddle.net/bateast/4SGsc/7/
So if you want to pass a DOM to .append(), try this instead:
d3.select(elt[0]).append(function() { return node[0]; });
You can solve this using a callback arrow function
d3.select(elt[0]).append(function() {()=> $compile('<div hello></div>')(scope)[0] });
Related
For some reason when using this function('testclickfn') as ng-click on dynamic elements, it doesn't invoke the function. Here is the angularjs file:
app.controller('testctrl',function($scope){
testfn($scope);
$scope.showelements = function(){
displayTestRows();
}
});
function testfn($scope){
$scope.testclickfn = function(){
alert('testing click fn');
};
}
function displayTestRows(){
for(var i=0; i < 5; i++){
$("#testdiv").append('<p ng-click="testclickfn()">click me</p><br>');
}
}
HTML page that calls angularjs controller 'testctrl':
<div id="testdiv" ng-controller="testctrl">
<button ng-click="showelements()">Show dynamic elements</button><br>
</div>
I'm assuming since the 'click me' tags are being generated after angular has loaded the page, it doesn't know of anything after page is generated so ng-click="testclickfn()" doesn't get registered with angularjs.
How do I get around this situation?
You're creating elements in a way angular has no idea about (pretty bad practice), but not to worry, you can let angular know!
Change the controller signature to
controller('testctrl', function($scope, $compile) {
Then run compile the new elements manually to get the ng-click directive activated
$scope.showelements = function(){
displayTestRows();
$compile($("#testdiv").contents())($scope);
}
If you cant tell, having to use jquery selectors inside your controller is bad, you should be using a directive and the link function to attach the element to the scope (ie, what if you have multiple testctrl elements?), but this'll get you running
As promised
The general rules are that no JS should be outside the angular functions, and that DOM manipulation, where appropriate should be handled by angular also.
Example 1: powerful
Have a look
<div ng-controller="ctrl">
<button ng-click="show('#here')">
create
</button>
<div id="here">
I'll create the clickables here.
</div>
</div>
use controllers for things that share stuff between a lot of different things
.controller('ctrl', ['$scope', '$compile', function($scope, $compile) {
$scope.sharedVariable = 'I am #';
$scope.show = function(where) {
where = $(where).html('');
//lets create a new directive, and even pass it a parameter!
for (var index = 0; index < 5; ++index)
$('<div>', {'test':index}).appendTo(where);
$compile(where.contents())($scope);
};
}])
use directives for non-unique elements that each have their own states
.directive('test', function() {
return {
//these too have their own controllers in case there are things they need to share with different things -inside them-
controller : ['$scope', function($scope) {
$scope.test = function() {
//see, no selectors, the scope already knows the element!
$scope.element.text(
//remember that parent controller? Just because we're in another one doesnt mean we lost the first!
$scope.$parent.sharedVariable +
$scope.index
);
}
}],
//no need to do things by hand, specify what each of these look like
template : '<p>click me</p>',
//the whole "angular way" thing. Basically no code should be outside angular functions.
//"how do I reference anything in the DOM, then?"; that's what the `link` is for: give the controller access using `scope`!
link : function(scope, element, attributes) {
//you can assign "ng-click" here, instead of putting it in the template
//not everything in angular has to be HTML
scope.element = $(element).click(scope.test);
//did you know you can accept parameters?
scope.index = Number.parseInt(attributes.test) + 1;
},
//just some set up, I'll let you look them up
replace : true,
restrict : 'A',
scope : {}
};
})
Example 2: Simple
But that is just a very generic and powerful way of doing things. It all depends on what you need to do. If this very simple example was indeed all you needed to do you can make a very simple, almost-all-html version:
<div ng-controller="ctrl">
<button ng-click="items = [1, 2, 3, 4, 5]">
create
</button>
<p ng-repeat="item in items" ng-click="test($event)">
<span>click me</span>
<span style="display:none">I am #{{item}}</span>
</p>
</div>
.controller('ctrl', ['$scope', function($scope) {
$scope.test = function($event) {
$($event.currentTarget).children().toggle();
};
}])
That's it, works the same almost
I am not sure if I am doing this correctly, but I am trying to convert something was in a controller to a directive because I want to use it multiple times and just change a few values, so instead of making many huge object literals, I will have just one and just change the values passed in. I am trying to bind chartConfig, but it doesn't seem to be working. Am I doing this wrong?
Here is my directive:
app.directive('percentageSquare', function(){
return {
restrict: 'E',
scope: {
bgClass: '#',
percentage: '#',
chartConfig: '='
},
link: function(scope){
var fontSize = 80;
var percentage = scope.percentage || 0;
scope.chartConfig = {
options: {
chart: {
// Chart settings here
}
}
};
},
templateUrl: '/templates/dashboard/charts/PercentageChart.html'
};
});
Here is the template that the directive is using (PercentageChart.html):
<div class="drop-shadow">
<div class="row">
<div class="col-sm-12">
<highchart config="chartConfig" class="{{bgClass||''}}" ng-show="true"></highchart>
</div>
</div>
</div>
Here is how I am calling the directive:
<percentage-square bg-class="bg-orange" percentage="23"></percentage-square>
Now my chartConfig no longer binds to the directive like it used to when it was in a controller. What can be done to fix this?
Edit
I have gotten a little further, this seems to work:
scope.$watch(scope.chartConfig, function(){
scope.chartConfig = {
// Chart Settings
};
});
But it seems to load the chart twice, as I get two animations.
Looks like what I want to do is watch chartConfig. it must also be wrapped in a string in order for it to work properly. Using scope.chartConfig loaded the chart twice, while 'chartConfig' loads the chart once and properly.
scope.$watch('chartConfig', function(){
scope.chartConfig = {
// Chart Settings
};
});
In my application i have a list of custom directive names.
$scope.data =["app-hello","app-goodby","app-goodafter"];
each name in this array is one directive that im created.
var app = angular.module('app',[]).controller('mainCtrl',function($scope){
$scope.data =["app-hello","app-goodby","app-goodafter"];
}).directive('appHello',function(){
return {
restrict:'EA',
template:'<h1>Hello Directive</h1>'
};
}).directive('appGoodbye',function(){
return {
restrict:'EA',
template:'<h1>GoodBye</h1>'
};
}).directive('appGoodafter',function(){
return{
restrict:'EA',
template:'<h1>Good Afternoon</h1>'
};
});
now i want to load directive with ng-repeat in the view for example because i used EA restrict for directive can create directive in ng-repeat like this :
<div ng-repeat="d in data" >
<div {{d}}></div>
</div>
but this way it doesn't work. so the real question is if i have list of directive how to load this directive with ng-repeat.for this scenario i create a jsbin .
thanks.
You need a "master" directive that $compiles the HTML (optionally containing directives) into an Angular-aware template and then links the compiled element to a $scope:
app.directive('master', function ($compile) {
return {
restrict: 'A',
link: function postLink(scope, elem, attrs) {
attrs.$observe('directive', function (dirName) {
if (dirName) {
var compiledAndLinkedElem =
$compile('<div ' + dirName + '></div>')(scope);
elem.html('').append(compiledAndLinkedElem);
}
});
}
};
});
<div master directive="{{dir}}" ng-repeat="dir in ['dir1', 'dir2', 'dir3']"></div>
See, also, this short demo.
You can do it in this way:
Directive:
app.directive('compile',function($compile){
return{
restrict:'A',
template: '<div></div>',
link:function(scope,elem,attrs){
scope.name = attrs.compile;
elem.children('div').attr(scope.name,'');
$compile(elem.contents())(scope);
}
};
});
HTML:
<div ng-repeat="d in data" compile="{{d}}">
</div>
Jsbin: http://jsbin.com/wofituye/4/edit
I actually prefer to create templates, that just contain the directive. Then you can use ng-include this then enables you to easily pass scope variables into the dynamically chosen directives too.
Here is my widget code fore example:
<div ng-repeat="widget in widgets track by $index" ng-include="widget.url" class="widget-container" ng-class="widget.widget_type.config.height +' ' + widget.widget_type.config.width">
</div>
Then I set the widget.url to a template containing just the right directive.
I can then in my directive do this:
<custom-widget ng-attr-widget="widget"></custom-widget>
Then I have access to the dynamic variable too, so I can access configuration specifics too, without having to dynamically generate HTML strings and compile them. Not a perfect solution, but personally I used to use the other approach mentioned, and discovered that this fit my needs much better.
I am new to angularjs.....I am trying to write a directive which adds some html before and after an element...html is as desired but data binding not happening ... please help
plunker link
my precompile function is as follows
var linkFunction = function(scope,element,attrs){
element.removeAttr("cs-options");
var html = getHTML(element);
element.replaceWith(html);
$compile(element.parent())(scope);
}
Here's a way simpler solution, I'm using transclude to have the contents of the element copied into the template.
app.directive('csOptions',["$compile",function($compile){
return{
restrict:'A',
transclude:true,
template:"<form><div ng-transclude></div></form>"
}
}])
http://plnkr.co/edit/fqHr6i
The data binding does not work because the getHTML() method not copying {{abc}} along with the element. You need to update the link method as:
var linkFunction = function(scope,element,attrs){
// do not miss {{abc}}
var $parent = element.parent();
element.removeAttr("cs-options");
var html = getHTML($parent);
// override the parent not the element otherwise
// there will be two instances of {{abc}}
$parent.html(html);
$compile($parent)(scope);
}
Demo: http://plnkr.co/edit/mckBVu1HfT4fp90Twvum
I have broken this problem down into it's simplest form. Basically I have a directive that, for the demo, doesn't yet really do anything. I have a div with the directive as an attribute. The values within the div, which come from an object array, are not displayed. If I remove the directive from the div, they are displayed OK. I am clearly missing something really obvious here as I have done this before without any problems.
Here's the Plunk: http://plnkr.co/edit/ZUXD4qW5hXvB7y9RG6sB?p=preview
Script:
app.controller('MainCtrl', function($scope) {
$scope.tooltips = [{"id":1,"warn":true},{"id":2,"warn":false},{"id":3,"warn":true},{"id":4,"warn":true}];
});
app.directive("cmTooltip", function () {
return {
scope: {
cmTooltip: "="
}
};
});
HTML
<div ng-repeat="tip in tooltips" class="titlecell" cm-tooltip="true">
A div element: {{ tip.id }}
</div>
<br><br>
Just to prove it works without the directive:
<div ng-repeat="tip in tooltips" class="titlecell">
A div element: {{ tip.id }}
</div>
There is a hack to make it working in earlier versions of angular by making use of transclusion, like that:
app.directive("cmTooltip", function () {
return {
scope: {
cmTooltip: "="
},
transclude: true,
template : '<div ng-transclude></div>'
};
});
PLNKR
As by Beyers' comment above and below, the behaviour the question is about no longer exists in at least 1.2.5
To be clearer; this has nothing to do with ng-repeat, you can remove it and there still will be no tip ( or tooltips ).
See this question on what the = and other configs mean and what it is doing for you.
Basically for your situation when you use = the scope of the directive will be used in the underlying elements, you no longer have your controller's scope. What this means for you is that there is no {{ tip.id }} or not even tip. Because the directive doesn't supply one.
Here's a plunker that demonstrates what you can do with it.
Basically all i did was
app.directive("cmTooltip", function () {
return {
scope: {
cmTooltip: "="
},
link: function($scope){ // <<
$scope.tip = { id: 1 }; // <<
} // <<
};
});
This creates the tip object on the scope so it has an id.
For your situation you would probably just not use = and look at this question for your other options depending on what you want.
In my opinion this isn't the way to go.
I would use Objects.
JS code:
function tooltip(id,warn){
this.id = id;
this.warn = warn;
}
tooltip.prototype.toString = function toolToString(){
return "I'm a tooltip, my id = "+this.id+" and my warn value = "+this.warn;
}
$scope.tooltips = [new tooltip(1,true),new tooltip(2,false),new tooltip(3,true),new tooltip(4,true)];
HTML:
<div ng-repeat="tip in tooltips" class="titlecell">
A div element: {{ tip.toString() }}
</div>