I have a directive coming in from a database. Similar to how shortcodes work in Wordpress, the user needs to be able to insert these custom galleries here and there. I've tried several, several ways. They compile but they do not affect the HTML on the page. What am I missing?
Incoming from database:
<p>Lorem Ipsum. Some content here</p>
<div work-gallery friendly="bq"></div>
I would like to replace that DIV with the "work-gallery" attribute with a template. When I load that content into the scope of my page, I compile it so my directive triggers.
From controller
$compile($scope.page.content)($scope);
This triggers the directive, it compiles right up to where it needs to append it or replace it and then just doesn't show up on the frontend. If I add that DIV outside of the dynamically loaded content, it works.
Directive
app.directive('workGallery', function ($compile) {
var template = '<div>TEST{{page.med.length}}</div>';
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.page.med = [1, 2];
scope.$watch(attrs.friendly, function () {
ele.html(template);
$compile(ele.contents())(scope);
console.log(ele);
ele.append(ele.contents());
});
}
};
});
Inspecting "element" reveals TEST2 if I dig through down to innerText but that's all I get. Any help is appreciated! From what I understand, this should add "TEST2" within my content.
Expected Output
<p>Lorem Ipsum. Some content here</p>
<div work-gallery friendly="bq">TEST2</div>
Any help is appreciated!
i think there is something wrong about watching an attribute, try:
attrs.$observe('friendly', function(val){
/* .... */
});
Related
CONTEXT
I need to load in my AngularJS (v1.4) app some HTML gotten from backend and insert it (the html) into my partial (already loaded). The partial has already some HTML loaded (and completely functional). Right now I'm able to load the HTML and compile it with a directive posted here (Compiling dynamic HTML strings from database). See code below.
PROBLEM
But...when part of the HTML is already loaded (partial loaded and functional) and then I get another HTML content from backend, and the directive is compiling that new one, the entire document (DOM) gets "freezed". I can't type on inputs or do any click on buttons, including those in my previous loaded HTML.
QUESTION
How could I load HTML content, $compile it in "background" or any other way that allows me to continue using the rest of the (already functional) HTML?
It is for me a requisite that the new html content that arrives gets compiled because it contains angular validations and so on that need to be compiled and get inside the "angular world" (be inside the angular digest cycle and so on).
This is the directive I'm using for compiling the html
(function () {
var dynamic = function($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
if (html) {
ele.html(html);
$compile(ele.contents())(scope);
}
});
}
};
};
dynamic.$inject = ['$compile'];
angular.module('app')
.directive('dynamic', dynamic);
}());
In the controller I've something like
// this will be filled with asynchronous calls were I get the HTMLs from a service
// in order to keep this example simple I just made a demo, not with the real async calls
$scope.secciones = []
//when the promises are getting resolved "secciones" would be something like (more items can be added after in time)
$scope.secciones = [
{html: "<div> some html content here (not too small sometimes) </div>"},
{html: "<div> another html content here (not too small sometimes) </div>"}
]
...and in the view
<!--every time an async call with html is resolved, it's added to secciones, then a new div is generated and compiled-->
<!-- if there was some html previously rendered and the app starts compiling new html the UI gets "freezed"-->
<div ng-repeat="item in secciones">
<div dynamic="item.html"></div>
</div>
Note: I'm using this approach because each html represents a tab in a tabpanel I have, in which the user actually sees only one html of all of them in "secciones" (the others are hidden, but still there), but I need to compile the others in order to get them ready for the user when he/she click that other tab (another html in secciones).
If there could be any solution to this by upgrading to a newer version of AngularJS(1.x), let's say 1.6, for instance. I'd would be glad to try it out.
Basically I have done this by getting html from script tag and compile it and append to existing div.
You can use following snippet.
Include div in your html
<div id="step-container">
</div>
Controller code
var template = $templateCache.get('basicInfo'); // or your html
$compile($("#step-container").html(template).contents())($scope);
$("#step-container").show();
For demonstration this will be included in html page
<script type="text/ng-template" id="basicInfo"></script>
In this way you can compile you html coming from backend.
Hope it helps.
You can try use this directive to compile the HTML code. This directive compile the code when to detect any change in variable htmlCode
module.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
element.html(value && value.toString());
var compileScope = scope;
if (attrs.bindHtmlScope) {
compileScope = scope.$eval(attrs.bindHtmlScope);
}
$compile(element.contents())(compileScope);
});
}
};
}]);
you can install via bower, DirectiveRepo
USAGE:
<div bind-html-compile="htmlCode"></div>
So in Angular i'm trying to do
$scope.data = "<script> alert('hi'); </script>";
But unfortunately that doesn't work. I also tried to add ng-bind-html but without any results.
{{data}}
also I tried to load data in a script tag but that also seems not to work. Is there a way to avoid this all? For example
$scope.data = "bob";
-
<script>
var name = {{data}};
</script>
You could create a directive that will load the script into DOM dynamically.
Markup
<load-script ng-if="data" data="data"></load-script>
Directive
app.directive('loadScript', function($compile){
return {
restrict: 'E',
scope: {
'data': '='
},
link: function(scope, element, attrs){
element.append($compile(scope.data)(scope))
}
}
})
Working Plunkr
Your $scope will be already either within a <script> block or in a Javascript file.
Now, when/how do you want the alert to be called? If I understand correctly what you're trying to do, here's how to do it:
<div ng-click="doAlert()">
Click here to see an alert
</div>
and in your controller:
$scope.doAlert = function() {
alert('hi);
};
I've a scenario which I want to run a custom directive on the DOM that ng-bind-htmlcreate.
Basicly I've to customize the behavior of the html tag <a> because the html that is loading is unsafe and when the user click the link I've to execute some functions before anything happens, aka, the click event of jqLite.
So my original ideia was create a directive that modifies the behavior of any <a> inside the container that I put the attribute of my directive.
This works fine, until I combine with ng-bind-html, my directive runs before the ng-bind-html compile the string into html and attached to the DOM.
So, is any way to run my custom directive after the ng-bind-html run?
DEMO
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-bind="sometext" my-directive>before</div>
</div>
Controller:
angular.module('myApp', []);
angular.module('myApp').controller('myCtrl', function($scope) {
$scope.sometext="stuff here";
});
Directive:
angular.module('myApp').directive('myDirective', function() {
return {
priority: 10, // adjust this value ;)
link: function(scope,element,attrs) {
scope.$watch(attrs.ngBind, function(newvalue) {
console.log("element ",element.text());
});
}
};
});
Use priority property inside directive to run your code after mg-bind
In an Angular (1.3) app, I am displaying list of records using ng-repeat. There is a directive with a template inside the ng-repeat. Within the template I'm using ShareThis controls which are activated after the DOM is loaded.
On initial load of the app, the ShareThis Javascript works correctly and activates the buttons. On route change it does not activate. I've found to references to activate the controls manually via stButtons.makeButtons() or stButtons.locateElements();, but I'm unsure where to call this function in the directive or page cycle. I've tried within:
the directive link function - using $timeout or scope.$watch
the template <script>stButtons.locateElements();</script> - activates before model binding
the controller after binding - activates before DOM rendered
My understanding is the function to activate needs to be called after binding and after DOM rendering, but Angular does not know when the DOM is ready. There is a method to dynamically render the ShareThis controls using only Javascript, but I want the HTML defined in the template not Javascript for this case.
I've seen several questions out there related, but none of the answers seem to work 100% for my scenario (and many are broken as of Angular 1.3).
item-list.html (view)
<div ng-repeat="item in vm.itemList">
<item-directive item="item"></item-directive>
</div>
item-list.cs (controller)
{ ... vm.itemList = getItems(...) ... }
item-directive.js (directive)
(function () {
angular.module('app');
function itemDirective() {
var directive = { templateUrl: 'item.html', link: linkFunc, controller: ItemDirective };
return directive;
function linkFunc(scope, element, attr, ctrl) { var item = scope.item }
}
ItemDirective.$inject = ['$scope'];
function ItemDirective($scope) { ... }
}
item.html (directive template)
...
<div class="item-share-section">
<span class='st_sharethis_large' st_url="{{vm.item.url}}" st_title="{{vm.item.name}}"></span>
</div>
...
if I understood well, you want to call the function after the dom is completely render, right? Try this inside the postLink of your directive:
$scope.$watch('viewContentLoaded', stButtons.locateElements())
While my solution is a little hackish, I still prefer it over using $watch, since that is inefficient. Instead, I initialize the function which loads the buttons when the particular view you want to load the buttons with is rendered. The technique is as follows:
Here is the function which you should put in your controller:
$scope.loadShareThis = function() {
stButtons.makeButtons();
}
You'd then add to your item-list.html as such:
<div ng-repeat="item in vm.itemList" ng-init="loadShareThis()">
<item-directive item="item"></item-directive>
</div>
The dynamic URL's might give you additional problems, but that's another issue all together.
I have got a piece of code in an angular application, that writes a navigation tree into a <div>. This tree may change its size depending on the model of mymodule.tree.folders. Now I want to write a directive class="scrollable", that adds the functionality of jquery.nicescroll to the wrapping <div>:
<div class="scrollable">
... here is my resizing tree ...
</div>
Now, I have to call the resize() function of nicescroll each time, the tree model mymodule.tree.folders changes. This is necessary to make this library work as expected, after the content changes its size.
My question now is: How do I put the model mymodule.tree.folders (it is an array) into my directive to be able to $watch() it there? I would like to write something like this:
<div class="scrollable" scrollable-watch="mymodule.tree.folders">
... here is my resizing tree ...
</div>
...in my template. Is this possible, to fetch this model from the templates scope or do I have to serialize the whole tree into an extra variable?
I found a way to access the model through the $parent scope:
'use strict';
angular.module('shared.directives.scrollable', []);
angular.module('shared.directives.scrollable').directive('scrollable', function() {
return {
restrict: 'C',
link: function(scope, element, attrs) {
scope.$watch('$parent.' + attrs.scrollableWatch, function(newValue, oldValue) {
console.log('Model changed!');
}, true);
}
};
});
It seems a bit hackish to access the parent scope, but because this is allways the caller scope, I think it is okay.