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.
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>
I have a directive that returns a template that does not appear to be sizing itself as it should. Elements in the template have their height set to 100%, however, it seems the parent's height (outside the directive) is not being set quick enough (also from 0 to 100%).
I do not have an issue if I refresh the page, this only comes up when resizing the window.
Example: http://codepen.io/sweatherly/pen/rLYPvE (decrease the window size, then refresh to see)
Please note the the example does not use a directive, just highlights the problem.
(function() {
"use strict";
angular
.module("ngApp")
.directive("currentCard", function() {
return {
templateUrl: 'components/orders/current/current-card.tpl.html',
scope: {
orders: "=",
cardTitle: "#cardTitle"
}
}
});
})();
Is it possible to somehow use $document.ready() on/with the template?
Edit: It turned out to be a stupid CSS issue (targeting wrong element), but I know understand a bit about directive's link function.
You can simply use the link function...
Link is a built in feature for directive, this function is executed when the directive is loaded or appears in the parent template.
Reference here ; example here
(function() {
"use strict";
angular
.module("ngApp")
.directive("currentCard", function() {
return {
templateUrl: 'components/orders/current/current-card.tpl.html',
scope: {
orders: "=",
cardTitle: "#cardTitle"
},
link: function(){
console.log("ready")
}
}
});
})();
You can use link function which will be executed after the template is loaded.
Usually any DOM manipulation, adding/removing event handlers should be done in link function.
Please refer difference between compile and link function .
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 know how to detect the document end while scrolling in plain JS, my problem is - how to implement that in AngularJS, I know I should attach the scroll event to both the $window and $document, my question is about where to implement the behavior?, directives?, services?, if anyone can show me what is the right way to implement that kind of detection in AngularJS I'll be very thankful.
After struggling with it for a long time- stumbled across the library: http://binarymuse.github.io/ngInfiniteScroll/documentation.html.
Based on your use-case, you could do something like:
<div infinite-scroll="addMoreItems()">
<div ng-repeat="item in items">Item number {{$index}}: {{$item}}</div>
</div>
As it allows you to attach this to any div- you could almost do anything in the function you want to.
Depending on what you're doing it can go in a combination of places. Typically when dealing with DOM manipulation (which is what I assume will be happening) you should use a directive - something like:
app.directive("scrollDetector", ["$document", "$window", function($document, $window) {
return {
restrict: "A",
link: function(scope, elem, attrs) {
angular.element($window).bind("scroll", function() {
//scroll logic here
});
}
}
}]);
And then implement the scroll-detector directive. (ex: <div scroll-detector></div>)
I've created three plunkrs to illustrate my problem. I'm trying to create an AngularJS Directive that will initialize foundation and apply the necessary javascript to the loaded template. At first I was trying to use ngInclude to add the Foundation 5 nav bar to all of the pages of my website. The top bar works as expected when the html is directly applied to a partial. When the html is added in a directive, such as ngInclude, the top bar looses all its functionality. I suspect that this was because foundation is not getting initialized after the template is added by the directive. As a solution I created a custom directive that would initialize foundation and compile the html template. Initializing foundation the way I do freezes the application. Anyone have a solution to this?
Trying to achieve this without resorting to Angular UI.
Example 1: HTML directly applied to the view. Works as expected, when you click on the menu dropdown the pages are displayed.
http://plnkr.co/edit/aQc6j2W9MpRuJo822gAF?p=preview
Example 2: ngInclude used to load template to dom. No functionality is achieved, when you click on the menu dropdown nothing happens.
http://plnkr.co/edit/fSS3FfYKFilMXsIkYUHg?p=preview
Example 3: Created separate directive to replace ngInclude that would initialize foundation, compile, and load the template to DOM. Can't provide a plunkr because it would just freeze up, but here is the code.
.directive('testdirective', function($compile) {
return {
restrict: 'AE',
templateUrl: 'partials/includes/nav.html',
link: function(scope, element, attrs) {
$compile($(document).foundation())(scope);
}
}
})
applied in partial by:
<div testdirective></div>
Do this:
link: function(scope, element, attrs) {
$compile(element.contents())(scope);
$(document).foundation();
}
If you compile the element itself, you create an infinite loop:
$compile(element)(scope); //fail
Always be sure that you only compile the element's contents:
$compile(element.contents())(scope); //win
It seems that you are compiling the whole document and creating the infinite loop.
You can probably just do this:
templateUrl: 'partials/includes/nav.html',
compile: function() {
$(document).foundation();
}
because the template will be automatically compiled so you don't have to do it manually.
Note: it's best practice to inject and use Angular's $document, which is a wrapper for document that helps in testing. $($document).foundation();