Angularjs: understanding a recursive directive - javascript

I found a great tree directive here. Original: http://jsfiddle.net/n8dPm/
I have been trying to understand the functioning of it through couple of other SO questions, 1,2 . I couldn't quite understand how the recursive calls to render the tree directive work. Mainly the compile function
When all the compile function called?
When is the $compile function cached in the varibale compiledContents (is this the link function?), and when is it appends? Why it is not append always?
--
compile: function(tElement, tAttr) {
var contents = tElement.contents().remove();
var compiledContents;
return function(scope, iElement, iAttr) {
if(!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope, function(clone, scope) {
iElement.append(clone);
});
};
},

The Ng site has some great documentation (some of the best around in my opinion). The overview of the Startup and Runtime loops are very helpful:
http://docs.angularjs.org/guide/concepts
At a high level, when Ng first starts it compiles the DOM starting at where ng-app is located (treated like just another directive by Ng). This means it goes through the elements and looks directives and expressions it needs to link up to the $rootScope (the root of all scopes that are part of the prototypical inheritance chain setup by the compiling/linking process). If it is a directive, the compile process is done on it as well. The compiling process takes all of the Ng directives it finds in the HTML and prioritizes them based on there assigned priority or assumes the priority is zero. When it has them all ordered it executes the compile function for the directive which returns the link function. In the above example there are two show link functions which I will annotate below along with other notes linking it to this explanation. the link function also is given the HTML that was in the element the directive was a attribute, class, or element on in the form of the transclude object.
The link functions are executed which links the scope and the directive along with producing a view. This may include the HTML/transclude so it can be added where the directive ng-transclude is in the template of the directive (which will have the same process applied to it with it's template being the transclude).
So here are my notes for the slightly corrected custom directive above:
module.directive("tree", function($compile) {
//Here is the Directive Definition Object being returned
//which is one of the two options for creating a custom directive
//http://docs.angularjs.org/guide/directive
return {
restrict: "E",
//We are stating here the HTML in the element the directive is applied to is going to be given to
//the template with a ng-transclude directive to be compiled when processing the directive
transclude: true,
scope: {family: '='},
template:
'<ul>' +
//Here we have one of the ng-transclude directives that will be give the HTML in the
//element the directive is applied to
'<li ng-transclude></li>' +
'<li ng-repeat="child in family.children">' +
//Here is another ng-transclude directive which will be given the same transclude HTML as
//above instance
//Notice that there is also another directive, 'tree', which is same type of directive this
//template belongs to. So the directive in the template will handle the ng-transclude
//applied to the div as the transclude for the recursive compile call to the tree
//directive. The recursion will end when the ng-repeat above has no children to
//walkthrough. In other words, when we hit a leaf.
'<tree family="child"><div ng-transclude></div></tree>' +
'</li>' +
'</ul>',
compile: function(tElement, tAttr, transclude) {
//We are removing the contents/innerHTML from the element we are going to be applying the
//directive to and saving it to adding it below to the $compile call as the template
var contents = tElement.contents().remove();
var compiledContents;
return function(scope, iElement, iAttr) {
if(!compiledContents) {
//Get the link function with the contents frome top level template with
//the transclude
compiledContents = $compile(contents, transclude);
}
//Call the link function to link the given scope and
//a Clone Attach Function, http://docs.angularjs.org/api/ng.$compile :
// "Calling the linking function returns the element of the template.
// It is either the original element passed in,
// or the clone of the element if the cloneAttachFn is provided."
compiledContents(scope, function(clone, scope) {
//Appending the cloned template to the instance element, "iElement",
//on which the directive is to used.
iElement.append(clone);
});
};
}
};
});
Whole thing working:
http://jsfiddle.net/DsvX6/7/

Related

Angular js adding attribute directive from another directive

Pretend I have this:
<span ng-bind="value" my-dir my-dir-param="value"></span>
So my-dir is a custom directive that adds another directive to an existing element.
I guess it gonna look like this (skipping everything except some props from dir. def. object:
...
priority: 1001,
terminal: true
compile: function(el, attrs) {
attrs.$set("some_directive", "placeholder_text");
var compiled = $compile(el, null, 1001);
return function linkFn(scope, el, attrs) {
compiled(scope)
...some extra logic here...
}
}
...
I've tried to do such away and the problem is that ng-bind will bind on value from the directive scope, not the outer scope. I don't want to affect scopes from which other directives absorb values. What I want is that by adding my-dir directive I will apply "some_directive" and that won't affect the values that other directives receive. Thank you

When using ngRepeat track by dont update DOM on move

For my particular application, I want to be able to use an ng-repeat on a custom directive and track by a property of the object.
The problem I'm running into is that I am intentionally not wanting my custom directive to be rendered in the DOM where it is written. I want to take the template (including the directive element) and some variables that exist in it's parent scope and have them compiled and appended inside some markup that is being generated by a 3rd party library.
This way I can write something like:
<my-directive ng-repeat="item in items track by item.id"
ng-click="someCtrl.doSomethingWithAService();">
</my-directive>
And have this code appended elsewhere where it functions the same way.
The collection that is being repeated over can change frequently, but I don't want to recreate the appended content, and want to be able to remove it when the scope of each directive instance is destroyed.
I've tried as many approaches as I can think of, and some have been "good enough". The main issue I'm running into now is that when the collection is updated, the tracked items that didn't change end up being added to the DOM where the markup was originally written.
So on first load, everything works. Update collection: directive logic doesn't run again and the element is appended back to where the ng-repeat was.
Any ideas?
Edit:
window.angular.module('my.module')
.directive('myDirective', ['myService',
function (myService) {
return {
restrict: 'E',
scope: true,
replace: true,
templateUrl: '/path/to/template.tpl.html',
compile: function (tElement, tAttributes) {
tElement.removeAttr('ng-repeat');
return {
post: function (scope, iElement, iAttributes, controller, transcludeFn) {
iElement.remove();
var item = myService.addItem(scope, iElement[0].outerHTML);
scope.$on('$destroy', function () {
// remove item added in service
});
}
};
}
};
}]);
The directive essentially looks like this.
Service:
window.angular.module('my.module')
.factory('myService', ['$compile', function ($compile) {
function addItem(scope, template) {
var element = angular.element(document.querySelector('some-selector'));
element.html('').append($compile(template)(scope));
}
return {
addItem: addItem
};
}]);

Passing into a directive without adding it to scope

I have a directive where a list(array) of items is passed in through the scope of the controller into the scope of the directive whereby the template of the directive then has access to the items.
I would like to have it so that the list of items is passed to the directive (where it is then used within the link function) and then not directly accessible through the directive's template.
i.e. if we had the following directive:
directive('itemList', function(){
return {
scope: {
items: '='
}
link: function(scope, elem, attrs){
var item-list = scope.items;
// ... want to manipulate first ...
}
}
})
the variable scope.items is now available to any template that the directive uses. Whereas I don't want that to be the case and would like to pass in something to the directive without making it known to the scope. Is this possible?
Since the directive scope pretty much by definition is the scope used by the directive's template, I don't see any obvious way of doing this in a strict information hiding way. But, why not just use a different name for the passed scope variable and what the template binds to? For example, if you said scope: { myPrivatePassedItems: '=items' }, you can now work with scope.myPrivatePassedItems as much as needed before setting it as scope.items. With this approach, the HTML in both the usage of the directive and the directive's template just sees "items", but internally your directive has its own "private" variable.
I should add that the above is the simple change needed for the one-way data flow from the consumer to the directive template. If you also need to update the original items array, you will also want to add a scope.$watch on the scope.items array after you have done your initial setup. You would then need to carry those changes (possibly with modifications) back to scope.myPrivatePassedItems in order to update the consumer's array.
You can use the $parse service to retrieve the value without using scope: {}, but you will lose the 2 way data binding that you inherently get from using scope: { items: '=' }. As mentioned by Dana Cartwright, if you need 2 way binding, you have to set this up manually with watches.
directive('itemList', function($parse){
return {
link: function(scope, elem, attrs){
var itemList = $parse(attrs['items'])(scope);
// do stuff with itemList
// ...
// then expose it
scope.itemList = itemList;
}
};
});

Angular directives - How to select template based on attribute values?

I am developing a widget where I want to render some messages/text one after another. I want to change the template of the message based on the type of message.
my current directive setup is as follows
directive('cusMsgText', function(){
return {
restrict: 'E',
template:function(elements, attrs){
return '<div></div>';
},
link: function($scope, iElm, iAttrs, controller) {
//add children to iElm based on msg values in $scope
}
};
});
The directive is used as follows
<div ng-repeat="(key, value) in chatUser.msg">
<data-cus-msg-text msg="value.type"></data-cus-msg-text>
</div>
Now my question are -:
Is it possible to return one of multiple strings (templates) from
template function itself based on the actual value of attribute
msg. I tried accessing attrs.msg in template function and it
return value.type.
If not then, Is it good to manipulate template under linker or I
need to move it to compile function?
To render a different template based on value.type you can use the ng-switch statement:
<div ng-switch="value.type">
<div ng-switch-when="type1">
//...template for type 1 here...
</div>
<div ng-switch-when="type2">
//...template for type 2 here...
</div>
</div>
Also, if I understood your second question: manipulation of the uncompiled directive should be done in the compile function, all the manipulation which occurs after compilation should go in the link function.
Docs for ngSwitch
EDIT: +1 to Sebastian for understanding what you wanted. However, what he is proposing is essentially reinventing the wheel, since it is essentially compiling and inserting the template manually (which is what ngSwitch does for you). Also, you can access the attributes you put on your directive through the attrs argument of the link function.
In the template function you don't have access to the scope of your directive. If you want to control what gets rendered you can do this using conditional logic (e.g. ng-switch) in a global template as suggested by simoned or use a link function:
.directive('cusMsgText', function($compile) {
return {
restrict: 'E',
scope: {
msg: '=',
item: '='
},
link: function(scope, element, attrs) {
templates = {
x: '<div>template x {{item.name}}</div>',
y: '<div>template y {{item.name}}</div>'
};
var html = templates[scope.msg];
element.replaceWith($compile(html)(scope));
}
};
});

AngularJs: create directive

I've a question about a directive I want to write. Here is the jsfiddle
This is the HTML
<div ng-controller="TestCtrl">
<mydir base="{{absolute}}">
<div>{{path1}}</div>
<div>{{path2}}</div>
</mydir>
</div>
The directive, called 'mydir', will need the value of the base attribute and all the path values (there can be any number of paths defined). I don't want to inject values from the controller directly into the directive scope (they need to be independent). I have 3 questions about this (checkout the jsfiddle too!)
1) although the code works as it is now, there is an error: "TypeError: Object # has no method 'setAttribute'". Any suggestions what is wrong?
2) in the directive scope.base is 'undefined' instead of '/base/'. Can this be fixed.
3) How can I make a list of all the path values in the directive ?
You need to set an isolate scope that declares the base attribute for this directive:
scope: {
base: "#"
}
This solves (2).
Problem (1) is caused from the replace: true in cooperation with the scope above, because it creates a comment node to contain the repeated <div>s.
For (3), add paths: "=" to scope and, of ocurse, pass them from the parent controller as an array.
See forked fiddle: http://jsfiddle.net/swYAZ/1/
You're creating an new scope in your directive by setting scope: true what you want to do is:
app.directive('mydir', function ($compile, $rootScope) {
return {
replace: true,
restrict: 'E',
template: '<div ng-repeat="p in paths"> {{base}}{{p}}/{{$index}}</div>',
scope: {
base : '='
},
link: function (scope, iElement, iAttrs) {
scope.paths = ['p1', 'p2'] ;
}
}
});
This will setup a bi-directional binding between your directive's local scope and the parent's scope. If the value changes in the parent controller it will change in the directive as well.
http://jsfiddle.net/4LAjf/8/
If you want to make a robust directive to be able to replace the data to its content (3)
You can pass a reference as an attribute and display the data accordingly.
See this article, look for wrapper widget.

Categories

Resources