Directive link function does not have access to the entire template DOM - javascript

I have a directive which has a template that recursively include a template. In my directive link function, I am unable to get the complete DOM with a selector.
Here is my directive. Notice that my directive try to call dropdown() function on all .ui.dropdown divs constructed so nested dropdown will be activated.
.directive("floatingDropdown", function() {
return {
restrict: 'E',
templateUrl: "scripts/Ui/FloatingDropdown.html",
replace: true,
scope: {
uiClass: '#',
model: '=ngModel',
optionTree: '='
},
link: function(scope, elem, attrs) {
scope.elemClass = scope.uiClass || "ui floating dropdown icon button";
$(elem).dropdown();
$(elem).find(".ui.dropdown").dropdown();
}
}
})
The scripts/Ui/FloatingDropdown.html contains a nested include. This creates multiple levels of dropdowns
<div class="{{elemClass}}">
<script type="text/ng-template" id="node_template.html">
<div class="ui dropdown" ng-if="option.options">
<span ><i class="dropdown icon"></i> {{option.value}}</span>
<div class="menu" ng-if="data.options">
<div class="item" ng-repeat="option in data.options" ng-include="'node_template.html'"></div>
</div>
</div>
<span ng-if="!option.options" ng-click="model=option">{{option}}</span>
</script>
<i class="dropdown icon"></i>
<div class="menu">
<div class="item" ng-repeat="option in optionTree.options" ng-include="'node_template.html'">
</div>
</div>
</div>
My problem is $(elem).find(".ui.dropdown") will not find the recursively generated divs by ng-include

By attempting to do DOM manipulation in a directive's link() method like that, you're trying to query/modify a part of the DOM that hasn't been rendered yet.
You need to defer those jquery calls until later. You can do this using:
$scope.$evalAsync(function() {
// DOM code
});
or
$timeout(function() {
// DOM code
}, 0);
Using $evalAsync will run the expression during the next $digest cycle, will allow you to modify HTML before it's rendered in the browser. Using $timeout will wait until all $digest cycles are complete.

Related

How to include multiple divs in a single directive?

I am trying to include multiple div's in a single directive.But the directive works on only first div and it leaves the other div's inside it.
Template code:
<div actor-check-box ng-repeat="actor in actors">
<div create-connections class="actor\{{$index}}" >
<span><input class="checkbox-actor" type="checkbox" name="actor-checkbox" id="actor-checkbox\{{$index}}">\{{actor}}</span>
</div>
<div ng-repeat="activity in activities">
<div ng-if="actor == activity.id">
<div ng-repeat = "impact in activity.text" >
<div update-connections class="impact\{{$index}}actor\{{actors.indexOf(actor)}}" actor-id="actor\{{actors.indexOf(actor)}}">
<span><input class="checkbox-activity" type="checkbox" name="impact-checkbox" id="activity-checkbox\{{$index}}actor\{{actors.indexOf(actor)}}" activity-check-box>\{{impact}}</span>
</div>
<div ng-repeat="feature in features">
<div ng-if="actor == feature.id && impact == feature.key">
<div feature-connection ng-repeat = "feature in feature.text" class="feature\{{$index}}" activity-id="impact\{{activity.text.indexOf(impact)}}actor\{{actors.indexOf(actor)}}" id="">
<span><input class="checkbox" type="checkbox" name="impact-checkbox" id="" >\{{feature}}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Directive Code:
angular.module('mainModule').directive('actorCheckBox', function($interval) {
return {
restrict: 'EA',
/*transclude: true,*/
link: function (scope, element, attrs, ctrl) {
scope.$watch('ngModel', function(newValue){
/*alert(newValue);*/
console.log(element.find('input[type="checkbox"]'));
/*console.log(element.find('input[class="checkbox-actor"]'));*/
console.log(element.find('input[class="checkbox-activity"]'));
console.log(attrs);
});
}
}
});
Output In console:
[input#actor-checkbox0.checkbox-actor, prevObject: o.fn.init[1], context: div.ng-scope, selector: "input[type="checkbox"]"]
[input#actor-checkbox1.checkbox-actor, prevObject: o.fn.init[1], context: div.ng-scope, selector: "input[type="checkbox"]"]
[input#actor-checkbox2.checkbox-actor, prevObject: o.fn.init[1], context: div.ng-scope, selector: "input[type="checkbox"]"]
So the problem is I have 3 div's and directive is applied on the first div
and 2 more div is inside the main div with checkbox. When the directive is called console only shows the checkbox element in main div not of other 2 div's. Adding the console out from directive as well:
If I inlude transclude: true it removes all the earlier directives on the element and page goes blank.
It's not happening because ng-repeat creates separate scopes for itself. You need to include in on the divs as well or modify your directive to not use isolated scopes.

Angular ui-router prevent state trigger inside directive

I have a directive clickable-tag for which i am passing my data as the tag's name (tag.tag):
<a class="item item-avatar"
ui-sref="nebula.questionData({questionId: question.id})"
ng-repeat="question in questionsData.questions">
<img src="{{question.user.profile_photo || '../img/avatar.jpg'}}">
<h2 class="question-title">{{question.title}}</h2>
<p>{{question.description}}</p>
<div class="question-tags-list" ng-repeat="tag in question.tags" clickable-tag data="{{tag.tag}}">
<button type="submit" class="tag">{{tag.tag}}</button>
</div>
</a>
The directive clickable-tag is inside a ui-sref (on the outer a tag). Inside the directive, I want the outer ui-sref to be prevented and instead the user should be directed to another state (the one i am specifying in the directive below).
.directive("clickableTag", function($state) {
return {
restrict: "A",
scope: {
data: "#"
},
link: function(scope, elem, attrs) {
elem.bind('click', function(ev) {
console.log('scope.tagName: ', scope.tagName);
if (scope.data) {
$state.go('nebula.tagData', {tagName: scope.data});
}
});
}
};
})
The problem is that only the resolve of the state specified inside the directive runs. The view which is actually rendered is of the state specified by the outer ui-sref.
Any solutions as to how to prevent the outer ui-sref from being triggered. and instead trigger a state change as specified inside the directive ?
Any help would be appreciated. Thanks.
Note: I have already tried preventDefault(), stopPropagation(), return false inside my directive.
Move the ng-repeat outside and above the <a> tag and move the close of the <a> tag above the button.
<div ng-repeat="question in questionsData.questions">
<a class="item item-avatar"
ui-sref="nebula.questionData({questionId: question.id})">
<img src="{{question.user.profile_photo || '../img/avatar.jpg'}}">
<h2 class="question-title">{{question.title}}</h2>
<p>{{question.description}}</p>
</a> <!--Put close of A tag here --->
<div class="question-tags-list" ng-repeat="tag in question.tags"
ng-click="$state.go('nebula.tagData', {tagName: tag.tag})">
<button type="submit" class="tag">{{tag.tag}}</button>
</div>
</div>
For more information see the AngularJS ng-click API Docs

how to use jQuery plugin (semantic-ui) in angularJS directive?

I use semantic-ui in my project, the pulgin is checkbox
someone say if use jQ plugin, you must use it in angular directive
but it doesn't work
the checkbox of semantic-ui setting in semantic-ui API document, you must set this to init checkbox
$('.ui.checkbox').checkbox();
I try to change it to angular like this:
app.html
<div class="ui animate list">
<div class="item ui toggle checkbox" todo-checkbox ng-repeat="item in day track by $index">
<input type="checkbox">
<label ng-bind="item.content"></label>
</div>
</div>
and this is directive in angularjs file
todoApp.directive('todoCheckbox', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
$(elem).checkbox();
}
};
});
but it doesn't work in my project. Why?
You're close. elem is the element of the directive. In this case it is
<div class="item ui toggle checkbox" todo-checkbox ng-repeat="item in day track by $index">
<input type="checkbox">
<label ng-bind="item.content"></label>
</div>
Now, if we use find to help us locate the input field within the elem, then we can select the input field and run the checkbox method.
todoApp.directive('todoCheckbox', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
angular.forEach(elem.find( "input" ), function(inputField) {
inputField.checkbox();
}
}
};
});
A bit late to the party but you should be able to just move the todo-checkbox to the input tag (same with the semantic ui specific attributes)
Try
angular.element(elem).checkbox();
instead of
$(elem).checkbox();

How to use the moment library in angular in a directive that uses compile instead of link

I have a tree of connected documents (parent to child) in my database from a single model called Actions, they're recursively compiled in an angular directive so that they're nested inside their parents.
I have the following code:
angular.module('crmDashboardApp')
.directive('actionDirective', function ($http, $compile, RecursionHelper) {
return {
scope: {
actionId: '=', // html:action-node, js:actionNode
actionList: '='
},
templateUrl: 'app/main/directive/action/action.directive.html',
replace: true,
restrict: 'E',
compile: function (element) {
return RecursionHelper.compile(element, function(scope, iElement, iAttrs, controller, transcludeFn){
scope.deleteAction = function (_action) {
var id = _action._id;
$http.delete('/api/actions', {
data: {'id':id},
headers: {"Content-Type": "application/json;charset=utf-8"} // we need to do this if we want to send params, otherwise we need to do traditional REST in URL
});
};
// Find for already called action list
scope.findAction = function (_id, _list) {
scope.actionNode = _.findWhere(_list, {_id:_id})
};
scope.findAction(scope.actionId, scope.actionList);
function calculateTimeSince(){
scope.fromNow = moment(scope.actionNode.content).fromNow(true);
}
setInterval(calculateTimeSince, 1000);
scope.fromNow = moment(scope.actionNode.content).fromNow(true);
});
}
};
});
This only compiles once on load and changing anything in the scope after does nothing. I want the setInterval function to change a variable scope.fromNow to be updated every second and update the view (the HTML references this with a simple {{fromNow}})
I believe I'll have to re-compile the directive somehow but doing something like:
$compile(element.contents())(scope)
within the setInterval function doesn't work.
My directive's HTML looks like this:
<div class="action-node">
<header>{{ actionNode.name }}</header>
<div class="row">
<h3 class="col-md-12">{{ actionNode.title }}</h2>
<h5 class="col-md-12">{{ actionNode.description }}</h5>
</div>
<div class="row">
<div class="col-md-3">Time Since: {{fromNow}}</div>
<div class="col-md-3">Content: {{ actionNode.content}}</div>
<div class="col-md-3">Duration Type:{{ actionNode.duration_type }}</div>
<div class="col-md-3">Type: {{ actionNode.type }}</div>
</div>
<div class="row">
<div class="col-md-4">
{{actionNode.children.length > 0 ? actionNode.children : "No children" }}
</div>
<form class="pull-right" ng-submit="deleteAction(actionNode)">
<input class="btn btn-primary" type="submit" value="Delete">
</form>
</div>
<div class="action-wrapper" ng-repeat="child in actionNode.children" ng-if="actionNode.children.length > 0">
<!-- <div class="row" ng-repeat="child in actionNode.children" ng-if="actionNode.children.length > 0" ng-style="{'margin-left': ({{actionNode.nest_level}}+1)*30+'px'}"> -->
<action-directive action-ID="child" action-list="actionList" />
</div>
</div>
You can see that it calls itself again right at the bottom. I am also using RecursionHelper so infinite loop isn't an issue.
Instead of using setInterval, you need to use the Angular wrapper service $interval.
$interval service synchronizes the view and model by internally calling $scope.$apply which executes a digest cycle.

Why can't I access the new DOM element created by Angular?

HTML:
<div class="list-group link-list" ng-show="linksForPerson">
<a href="" class="list-group-item" ng-repeat="link in linksForPerson" ng-click="showLinkDetail(link)" ng-class="{active: isSelectedLink(link)}">
<h4 class="list-group-item-heading">[[ link.engine.name ]]</h4>
<p class="list-group-item-text">[[ link.engine.base_url ]]</p>
<p class="list-group-item-text" ng-show="link.user_sync_id">[[ link.user_sync_id ]]</p>
<p class="list-group-item-text" ng-show="link.group_sync_id">[[ link.group_sync_id ]]</p>
</a>
<span class="glyphicon glyphicon-plus"></span> Add a new link
</div>
Controller:
appModuleLightDashboard.controller('ManageLinksController',
function($scope, $http, $timeout) {
$scope.addLink = function(event) {
$scope.linksForPerson.push({});
// Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.0-rc.1/$rootScope/inprog?p0=%24apply
$('.link-list .list-group-item').eq(-2).trigger('click');
// But this works ---- why?
// $timeout( function(){$('.link-list .list-group-item').eq(-2).trigger('click')} , 0);
}
});
I have changed the interpolate symbol to [[]] as it conflicts with Django
The problem:
A new list item will be created when the user clicks on the "Add a new link". I wanted to select this new list item automatically.
But it looks like I couldn't select that new DOM element created by Angular ( i.e. $('.link-list .list-group-item') doesn't return the new one ), unless I wrap the code with $timeout. Anyone knows why?
Also, please advise if there is a more Angular way to achieve it:)
Your question is "why". The answer is because at the moment you are trying to use jQuery to find the element, it hasn't yet been added to the DOM. That doesn't happen until the digest cycle runs.
$timeout works because the function call is now deferred until after the next digest cycle. The problem with that solution is that there are cases where the DOM still won't yet have been modified.
Looking in more detail, this will have several failure modes. The error you are showing is sent because you are actually triggering a click in the second to last element already added, and you are doing it from inside of a digest cycle. If you already have two or more items added to the collection, this triggers angular's ng-click on the second to last one (which happens to not be the one you think), which assumes it is called outside of a digest cycle and calls $apply, which fails with the error you see because it's actually inside of a digest cycle.
The "angular way" to achieve what you want is to use a directive.
.directive('triggerClick', function($parse) {
return {
restrict: 'A',
link: function(scope, elem, attr) {
var fn = $parse(attr['triggerClick']);
if(scope.$last) { //or some other logic
fn(scope);
}
}
}
})
div class="list-group link-list" ng-show="linksForPerson">
<a href="" class="list-group-item" ng-repeat="link in linksForPerson" ng-click="showLinkDetail(link)" ng-class="{active: isSelectedLink(link)}" trigger-click="showLinkDetail(link)">
<h4 class="list-group-item-heading">[[ link.engine.name ]]</h4>
<p class="list-group-item-text">[[ link.engine.base_url ]]</p>
<p class="list-group-item-text" ng-show="link.user_sync_id">[[ link.user_sync_id ]]</p>
<p class="list-group-item-text" ng-show="link.group_sync_id">[[ link.group_sync_id ]]</p>
</a>
<span class="glyphicon glyphicon-plus"></span> Add a new link
</div>
This works because the link function of the directive will be called after the node has been constructed and added to the DOM. Note the addition of "trigger-click" to your ng-repeat element.
elem in the directive is a jQuery object wrapped around the instance of the ng-repeat item. Angular will call the link function for every instance of the directive, which in this case is every instance of the ng-repeat.
Even more "angular" would be to not use a click event at all. You don't include the implementation of showLinkDetail, but rather than trigger a click, just call it in your controller.
As a general "angular" rule, anything that looks like jQuery should only happen in a directive.
EDIT: With more info on what you need, you can do this without need to do any DOM manipulation at all (no directives).
appModuleLightDashboard.controller('ManageLinksController',
function($scope, $http, $timeout) {
$scope.activeLink = undefined;
$scope.addLink = function(event) {
$scope.activeLink = {};
$scope.linksForPerson.push($scope.activeLink);
}
$scope.showLinkDetail = function(link){
$scope.activeLink = link
}
$scope.isSelectedLink = function(link){
return $scope.activeLink === link;
}
});
<div class="list-group link-list" ng-show="linksForPerson">
<a href="" class="list-group-item" ng-repeat="link in linksForPerson" ng-click="showLinkDetail(link)" ng-class="{active: isSelectedLink(link)}">
<h4 class="list-group-item-heading">[[ link.engine.name ]]</h4>
<p class="list-group-item-text">[[ link.engine.base_url ]]</p>
<p class="list-group-item-text" ng-show="link.user_sync_id">[[ link.user_sync_id ]]</p>
<p class="list-group-item-text" ng-show="link.group_sync_id">[[ link.group_sync_id ]]</p>
</a>
<span class="glyphicon glyphicon-plus"></span> Add a new link
</div>
you should not put your "add new link" inside the div with ngShow because when the linksForPerson array is empty, you will not be able to add a new link . Also, putting it outside the div will ease up every other manipulation (based on what you want to achieve"
linksForPerson is an array, use ng-show="linksForPerson.length" instead
you should initialize your arrays before pushing anything into it $scope.linksForPerson=[]
use of ng-bind is a better alternative to {{}} or [[]]
I refactored your code.
// ---- controller
appModuleLightDashboard.controller('ManageLinksController',
function($scope, $http, $timeout) {
var activeLink;
// you should initiate your array
$scope.linksForPerson = [];
$scope.isSelectedLink = function (link) {
return activeLink === link;
};
$scope.addLink = function(event) {
activeLink = {
engine: {
name : "engine" + ($scope.linksForPerson.length + 1),
base_url : " someUrl"
}
};
$scope.linksForPerson.push(activeLink);
};
});
and html (note use of ng-bind)
<div ng-controller="ManageLinksController">
<div class="list-group link-list" ng-show="linksForPerson.length">
<a href="#" class="list-group-item" ng-repeat="link in linksForPerson" ng-click="showLinkDetail(link)" ng-class="{active: isSelectedLink(link)}">
<h4 class="list-group-item-heading" ng-bind="link.engine.name"></h4>
<p class="list-group-item-text" ng-bind="link.engine.base_url"></p>
<p class="list-group-item-text" ng-show="link.user_sync_id" ng-bind="link.user_sync_id"></p>
<p class="list-group-item-text" ng-show="link.group_sync_id" ng-bind="link.group_sync_id"></p>
</a>
</div>
<span class="glyphicon glyphicon-plus"></span> Add a new link
</div>
here's jsfiddle for you to play with

Categories

Resources