Insert directive dynamically and compiling - angularjs

I have a scenario when a user click a link, I would like to insert a custom element into the DOM for example
//user clicks
$scope.click = function () {
var el = $compile("<my-directive></my-directive>")($scope);
$element.after(el);
};
The my-directive.... directive has an html template.. say for example (template1.html)
<p>My Template for my-directive</p>
{{SomeProperty}}
my-directive is defined like this
module.directive('myDirective', ['$compile', function ($compile) {
return {
restrict: 'E',
replace: true,
templateUrl: '/template1.html',
scope: true
};
}]);
If we assume the scope in myDirective acutally has a value for SomeProperty after running this code I will indeed have the my-directive inserted into the DOM and replaced by the template - template1.html however the {{SomeProperty}} has not been replaced at all! How do I do this??
See Plunkr for more details

You did $compile("<my-directive></my-directive>")($scope.$parent); in your Plunkr. Remove .$parent
Chenge template to:
<p>My Template for my-directive</p>
{{d.SomeProperty}}
As you did d in data.
It works then :)

I'm not sure if you had any other errors, but I found that removing replace:true made it work for me.
I'm not sure exactly what is happening here, but somehow the interaction of you adding the directive to the dom + replacing it immediately causes it not to work.
Another thing I noticed was that by using $element.after(el); you are ending up with an element that is OUTSIDE the controller's scope. It's not in the div that the controller has scope for. Unfortunately, I only saw this in MY plunkr, so don't know if this affected you also.
Plunkr here

Related

Run 'ng-click' inside a directive's isolated scope

Thanks in advance for taking the time to look into this question
I have serverside generated code that renders a directive wrapped around pre-rendered content.
<serverside-demo color="blue">
<p><strong>Content from Server, wrapped in a directive.</strong></p>
<p>I want this color to show: <span ng-style="{color: color}">{{color}}</span></p>
<button ng-click="onClickButtonInDirective()">Click Me</button>
</serverside-demo>
This means that 1.) the directive tag, 2.) the content inside the directive tag, 3.)the ng-click and 4.) The curly braces syntax are all generated by the server.
I want AngularJs to pick up the generated code, recompile the template and deal with the scope.
The problem is that I am having trouble getting it working. I understand that because the ng-click is inside the controller block, it is picked up not by the directive isolated scope, but the parent controllers. Instead I want the opposite... to pick up the onClickButtonInDirective scope function inside the serversideDemo link
I have created a jsfiddle best explaining my problem, which aims to clearly demonstrate the working "traditional" way of loading the template separately (which works) comparing it to the server-side way.
https://jsfiddle.net/stevewbrown/beLccjd2/3/
What is the best way to do this?
Thank you!
There are two major problem in your code
1- directive name and dom element not matched, - missing in dom element
app.directive('serverSideDemo', function() {
use <server-side-demo color="blue"> instead of <serverside-demo color="blue">
2- you need to compile the html code of server-side-demo dom with directive scope in link function
$compile(element.contents())(scope);
Working jsfiddle
Use templateUrl instead of template to fetch the content of directive from server:
app.directive('serverSideDemo', function() {
return {
restrict: 'AE',
scope: {
color: '='
},
templateUrl: 'link/that/returns/html/content',
link: function(scope, element, attrs) {
scope.onClickButtonInDirective = function() {
console.log('You clicked the button in the serverside demo')
scope.color = scope.color === 'blue' ? 'red' : 'blue';
}
}
};
});
Have a look at angular docs for more details

how to insert an angular 1.5 component with ng-bind-html

I have a component, and i would like to inject it dynamically into my html.
I have a component like this:
angular.module('test1', []);
angular.module('test1').component('test1', {
templateUrl: 'components/test1/test1.template.html',
controller: function test1Controller($scope) {
}
});
the test1.template.html file looks like this:
<p>TEST 1</p>
on my controller i have this:
angular.module('myApp')
.controller('ctrlCtrl', function ($scope, $sce) {
$scope.tag = "<test1/>";
});
on my index.html, i have this:
<ng-bind-html ng-bind-html="tag"></ng-bind-html>
but the tag will not show up. I have tried writing literaly "'<p>hi!</p>'" on the ng-bind-html field, and the text "hi!" shows up on a paragraph, so i don't think this error is because of a typo.
I also tried to use $sce.trustAsHtml, but it didn't work neither :(
$scope.tag = $sce.trustAsHtml("<test1/>");
when i insert an input field, the trustAsHtml method does work, but when i try to inject my components dynamically, it just won't let me, please help D:
Why ng-include won't work?
Components need to be compiled before you can use them on the markup. Try editing the html of the app with the developer tools from your browser, by artificially injecting your component on the markup: it won't work.
How to dynamically include components?
you'll need to use directives, this tutorial (thanks to #Artem K.) is friendly to follow, but you can also read the angular's official documentation, it is a little hard to understand though.
Following the logic of the final example of the angular's official documentation, you can create a directive that compiles everything that is passed to it, like this:
// source: https://docs.angularjs.org/api/ng/service/$compile
angular.module('myApp')
.directive('my-compile', function ($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
});
and then, on your index.html, you'll have to invoke the directive, sending the the string containing the component's tag as an argument.
<div compile="tag"></div>
As #charlietfl and #Artem K. said, you have to understand the angular's $compile so, thanks guys for pointing me in the right direction :)

How to add class directive after element is compiled and linked

I have a directive:
.directive('test', function(){
return {
restrict: 'C'
....
}
})
I would like to have this directive conditionally added to an element:
<div ng-class="{test: testActive}">
This doesn't work (here is a Plunk with the variations I've tried so far).
I'm guessing it would work if I $compiled() the element again, but I'm guessing calling $compile on an already $compiled() element comes with it's own set of problems (or is this something angular supports?).
Looking for suggestions/alternatives.

ng-click in directive doesn't work in IE but works in Chrome

I'm not sure if this is a known bug (or even a bug...) or not but I can't find it on the angular issues list, maybe I'm doing something wrong:
.directive('clickTest', function () {
return {
transclude: true,
template: '<div ng-click="click()" style="width:200px; height:200px;">Click me<div ng-transclude></div></div> Clicked {{clicked}} times',
controller: function($scope, $element){
$scope.clicked = 0;
$scope.click = function() {
$scope.clicked++;
}
}
}
So I've essentially added the directive to an element on my page. The directive has an ng-click handler in the template and transcludes the existing elements. The ng-click runs the click() function which should trigger the click on the current scope.
In Chrome when I click the button the counter goes up by 1.
If I do the same in IE11 nothing happens. I've been trying to get this working for a while as most of my target audience will be using IE
I think that this should work - as far as I can tell, angular should compile the template after transclusion to identify any further directives it needs to work with
Am I doing something wrong or should this click work?
Knew it would be something I was doing wrong - as commenters suggested it's because I tried to add the directive to a <button> element.
I wrapped the element in a <div> instead and applied the directive to that and it works!

angularJS directive with isolated scope, attribute binding doesn't work

Please see this jsfiddle: http://jsfiddle.net/viro/DK5pC/3/
What I did looks right compared to the tutorials and replies I've found, so I'm sure I'm overlooking something trivial.
I'm trying to do a directive on a html element, that will create a sibling div to display a message associated with the original element.
for example, for this html :
<input ng-model="inp" tst-msg="message" />
I would create as a sibling element:
<div class="msg">Msg:<span ng-bind="tstMsg"></span></div>
I was hoping that tstMsg in the div's scope would be bound to message in the input's scope.
Here's what the directive looks like :
angular.module('tst', [])
.directive('tstMsg', function(){
var template = "<div class='msg' >Msg:<span ng-bind='tstMsg'></span></div>";
var link = function(scope,element,attrs) {
element.parent().append(template);
console.log("link called");
};
return {
restrict: 'A',
scope: {
tstMsg: '='
},
link: link
};
});
Well that doesn't work and I can't figure out why.
You need to $compile the template you're adding to the DOM. Angular hasn't had a chance to add it's handlers, for instance the ng-bind directive to that part of the dom.
So instead of just adding the element like this:
element.parent().append(template);
These steps will let Angular process your template and then add it.
newe = angular.element(template);
$compile(newe)(scope);
element.parent().append(newe);
Updated fiddle

Resources