If you have a directive that you're using multiple times on a page how can 1 directive communicate with another?
I'm trying to chain directives together in a parent child relationship. When directive A is clicked i want to filter Directive B to only have the children of the selected item in Directive A. In this case there may be infinite number of directives and relationships on the page.
Normally i would have Directive A call a filter method on each of it's children, and each child calls it's child to continue filtering down the hierarchy.
But i can't figure out if calling methods from 1 directive to another is possibe.
Thanks
It sounds like you are looking for a directive controller. You can use the require: parameter of a directive to pull in another directive's controller. It looks like this:
app.directive('foo', function() {
return {
restrict: 'A',
controller: function() {
this.qux = function() {
console.log("I'm from foo!");
};
},
link: function(scope, element, attrs) {
}
};
});
app.directive('bar', function() {
return {
restrict: 'A',
require: '^foo',
link: function(scope, element, attrs, foo) {
foo.qux();
}
};
});
From the angular docs, here are the symbols you can use with require and what they do.
(no prefix) - Locate the required controller on the current element.
? - Attempt to locate the required controller, or return null if not found.
^ - Locate the required controller by searching the element's parents.
?^ - Attempt to locate the required controller by searching the element's parents, or return null if not found.
Here's a jsbin of my example. http://jsbin.com/aLikEF/1/edit
Another option that may work for what you need is to have a service that each directive sets up a watch on and can manipulate. For example, directive1 may watch a property in the service and respond to changes and also setup a button that can change that property. Then, directive2 can also watch and change the service, and they will respond to one another however you set that up. If you need a jsbin of that also, just let me know.
I hope this helps!
You could try putting all of the data into a service that the directives can each reference.
Something like:
app.factory('selectedStuffService', function(){
var allItems = [];
var selectedItems = [];
function addSelectedItem(item){
selectedItems.push(item);
}
return {
allItems: allItems,
selectedItems: selectedItems,
addSelectedItem: addSelectedItem
}
}
Interactions in directive A change the values in the selectedItems array and directive B can bind to it. You can easily add other methods to the service to filter/manipulate the items as needed and any directive that uses the service should be able to update based on changes made by other directives.
Related
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
};
}]);
I am relatively new to AngularJS. While venturing into directive creation, I can across this problem: How to dynamically add / remove attributes on the children of the directive's element when these children are dynamically added with 'ng-repeat'?
First, I thought of this solution:
template
...
a.list-group-item(ng-repeat='playlist in playlists', ng-click='addToPlaylist(playlist, track)', ng-href='playlist/{{ playlist._id }})
...
*directive
link: function(scope, elm, attrs) {
var listItems = angular.element(element[0].getElementsByClassName('list-group-item')
angular.forEach(listItems, function(item, index) {
'add' in attrs ? item.removeAttr('href') : item.removeAttr('ng-click');
listItems[index] = item;
}
...
Result
It turns out, my code never enters this angular.forEach loop because listItems is empty. I suppose it's because the ng-repeat is waiting for the scope.playlists to populate with the data from a async call to a server via $resource.
temporary fix
in the directive definition, I added a boolean variable that checks for the presence of 'add' in the element's attributes: var adding = 'add' in attrs ? true : false;
And then in the template,
a.list-group-item(ng-if='adding', ng-repeat='playlist in playlists', ng-click='addToPlaylist(playlist, track)')
a.list-group-item(ng-if='!adding', ng-repeat='playlist in playlists', ng-href='playlist/{{playlist._id }}')
While it works fine, it is obviously not DRY at all. HELP!
Instead of removing attributes, change your click handler.
Add $event to the list of arguments and conditionally use preventDefault().
<a ng-click='addToPlaylist($event,playlist)' ng-href='playlist'>CLICK ME</a>
In your controller:
$scope.addToPlaylist = function(event,playlist) {
if (!$scope.adding) return;
//otherwise
event.preventDefault();
//do add operation
};
When not adding, the function returns and the href is fetched. Otherwise the default is prevented and the click handler does the add operation.
From the Docs:
$event
Directives like ngClick and ngFocus expose a $event object within the scope of that expression. The object is an instance of a jQuery Event Object when jQuery is present or a similar jqLite object.
-- AngularJS Developer Guide -- $event
The way that you are trying to do things may not be the most Angularish (Angularist? Angularyist?) way. When using angular.element() to select child elements as you are trying to do here, you can make sure the child elements are ready as follows:
link: function(scope, elm, attrs) {
elm.ready(function() {
var listItems = angular.element(element[0].getElementsByClassName('list-group-item')
angular.forEach(listItems, function(item, index) {
'add' in attrs ? item.removeAttr('href') : item.removeAttr('ng-click');
listItems[index] = item;
}
});
}
However, this is unlikely to work in your situation, as #charlietfl points out below. If you want to avoid the solution you already have (which I think is better than your first attempt), you will have to reimplement your code altogether.
I would suggest defining an additional directive that communicates with its parent directive using the require property of the directive definition object. The new directive would have access to an add property of the parent (this.add in the parent directive's controller) and could be programmed to behave accordingly. The implementation of that solution is beyond the scope of this answer.
Update:
I decided to give the implementation something of a shot. The example is highly simplified, but it does what you are trying to do: alter the template of a directive based on the attributed passed to it. See the example here.
The example uses a new feature in Angular 1: components. You can read more about injectable templates and components here. Essentially, components allow you to define templates using a function with access to your element and its attributes, like so:
app.component('playlistComponent', {
// We can define out template as a function that returns a string:
template: function($element, $attrs) {
var action = 'add' in $attrs
? 'ng-click="$ctrl.addToPlaylist(playlist, track)"'
: 'ng-href="playlist/{{playlist._id}}"';
return '<a class="list-group-item" ng-repeat="playlist in playlists" ' +
action + '></a>';
},
// Components always use controllers rather than scopes
controller: ['playlistService', function(playlists) {
this.playlists = playlists;
this.addToPlaylist = function(playlist, track) {
// Some logic
};
}]
});
I have a directive that is repeated using ng-repeat. Consider this code:
<my-drctv todos="todos" ng-repeat="todos in todoGroups track by todos[0].id"></my-drctv>
todoGroups is a two dimensional array, that contains grouped todos.
This is my directive:
angular.module('myModule').directive('myDrctv', function() {
return {
restrict: 'E',
scope: {
todos: "="
},
replace: true,
templateUrl: '<div>{{firstTodo.description}}</div>',
link: function link(scope, element, attrs, ctrl) {
console.log("myDrctv: link fn");
scope.firstTodo = scope.todos[0];
}
};
});
This lists my todos (the template is simplified) and works so far.
Now the problem: When todoGroups is re-fetched from my server and set to a new value with $scope.todoGroups = myService.fetch() inside my controller, my directives aren't updated, because the link function of my directive isn't called a second time.
It seems that this problem occurs only, when the length of the list returned by the server is the same as before and only the "content" of my todos are changed (but I'm not sure)
Does angular re-use my directives for performance reasons? I always thought, it would destroy every element inside ng-repeat and insert new elements (in my case a directive)
How can I trigger a second call to my link function of my directive?
I have a directive(parent-directive) containing a slider(mySlider), that on stop event, call an angular $resource service with 2 params and the service return an object.
Directives structure:
<parent-directive>
<div ui-slider="slider.options" ng-model="mySlider" id="my-slider">
<span child-directive-one></span>
<span child-directive-two></span>
<span child-directive-three></span>
<div>
<span child-directive-four></child-directive-four>
</div>
</parent-directive
Whenever the user drag the slider, the service is called with different params and retieve new result, based on it I need to update the child directives.
I have in mind three ways:
using ng-model for all child elements instead directives, binding them on the scope of a controller in parent-directive;
the second one, that I don't know how to do it, is to create a controller in the parent-directive, that send and receive data from the service and share it to child-directives in order to update them.
the last one is to to create a state variable in the service and update it using a controller like to point 1.(see it above) and use a $watch to supervise the variable state and when it's changed then update the child-directives.
How should I proceed?
Please have a look here to see a brief code:
http://jsfiddle.net/v5xL0dg9/2/
Thanks!
ngModel is intended for two way binding, i.e. controls that allow the user to interfere with the value. From the description, it seems they are display-only components. So I would advise against using the ngModel.
Normally child directives require their parent. This allows them to call methods on the parent controller. What you need is the opposite: the parent controller needs to call methods on the children. It can be done: the children call a registerChild() method, and the parent iterates all registered children when it needs to call them. I find this implementation cumbersome.
Services are globals/singletons. I would vote against tying the service implementation to the UI needs.
My advice looks like your implementation of option 3, but with the parent controller holding the data:
1) Place the data you want to share with the child directives in a member variable of the parent controller:
myApp.directive('parentDirective', ['myService', function(myService){
...
controller: function($scope) {
...
this.sharedThing = ...;
}
}]);
The sharedThing can be updated when the service returns new data, or any other time it is necessary.
2) Have the children require the parent (just like your option 2), and watch this property:
myApp.directive('childDirectiveOne', function() {
return {
...
require: 'parentDirective',
link: function(scope, elem, attrs, parentDirective) {
scope.$watch(
function() {
return parentDirective.sharedThing;
},
function(newval) {
// do something with the new value; most probably
// you want to place it in the scope
}
});
}
};
});
Depending on the nature of the data, a deep watch may be required.
I have this two directives, one nested inside each other :
<envato class="container content-view-container" data-ng-cloak data-ng-hide="spinner">
<items data-ng-repeat="items in marketplaces"></items>
</envato>
And each of those two are defined as such :
Application.Envato.directive("envato", ["$timeout", function($timeout){
var object = {
restrict : "E",
controller : "EnvatoAPIController",
transclude : true,
replace : true,
templateUrl : "templates/envato-view.php",
link : function(scope, element, attrs, controller) {
console.log(scope);
return controller.getLatestItems().then(function(data) {
scope.marketplaces = angular.fromJson(data);
scope.count = scope.marketplaces.length;
var tst = angular.element(element).find(".thumbnails");
/* $timeout(function() { scope.swiper = new Swipe(document.getElementById('swiper-container')); }, 5000); */
scope.spinner = false;
});
}
};
return object;
}]);
Application.Envato.directive("items", function(){
var iterator = [],
object = {
require : "^envato",
restrict : "E",
transclude : false,
replace : true,
templateUrl : "templates/envato-items-view.php",
link : function(scope, element, attrs, controller) {
iterator.push(element);
if (iterator.length === scope.$parent.$parent.count) { console.log(iterator); };
}
};
return object;
});
A lot of the code above might not make a lot of sense because it's part of a bigger application, but I hope it does for my question. What I'm trying to do is to change a scope property of the directive envato from the directive items. Because I have a iteration and I want to know when it's done so I can do another operation on the appended DOM elements during that iteration.
For instance let's say I will have the scope.swipe defined inside the directive envato, and watch it for changes. In the directive items, I will watch when the ng-repeat is done and then change the above defined scope property scope.swipe. This will trigger the change inside the directive envato, and now I will know that I can do my operation.
I hope that I'm clear enough, if not I could try having more code or I'll try being more specific. How could I achieve what I just described above ?
EDIT : I do know that using : console.log(angular.element(element.parent()).scope()); inside the directive items will give me the scope of the envato directive, but I was wondering if there was a better way of doing it.
For this kind of inter-directive communication, I recommend defining an API/method on your envato directive that your items directive can call.
var EnvatoAPIController = function($scope) {
...
this.doSomething = function() { ... }
}
Your items directive already requires the envato directive, so in the link function of your items directive, just call the the API when appropriate:
require : "^envato",
link : function(scope, element, attrs, EnvatoCtrl) {
...
if(scope.$last) {
EnvatoCtrl.doSomething();
}
}
What is nice about this approach is that it will work even if you someday decide to use isolate scopes in your directives.
The tabs and pane directives on the AngularJS home page use this communication mechanism. See https://stackoverflow.com/a/14168699/215945 for more information. See also John's Directive to Directive Communication video.
Use scope.$eval('count') at item directive and let angular resolve for you.
I think you are looking for a callback that gets called when the ng-repeat completes. If that's what you want, i have created a fiddle. http://jsfiddle.net/wjFZR/.
There is no much of UI in the fiddle. Please open the firebug console, and run the fiddle again. You will see an log. That log is called at the end of an ng-repeat defined in the cell directive.
$scope.rowDone = function(){
console.log($scope)
} this is the callback function that is defined on the row directive that will get called when the ng-repeat of the cell directive is completed.
It is registered in this way.
<cell ng-repeat="data in rowData" repeat-done="rowDone()"></cell>
Disclaimer: I'm too a newbie in angularjs.
Hmmm it appears you are trying to make it difficult for yourself. In your directive you do not set a scope property:
var object = {
restrict : "E",
transclude : true,
replace : true,
scope: true,
...
Setting scope: {} will give your directive an fully isolated new scope.
BUT setting scope: true will give your directive a fully isolated new scope that inherits the parent.
I use this method to contain the model in the top level parent directive and allow it to filter down through all the child directives.
I love Mark's answer but I eventually created an attribute directive to save element directives' scopes to the rootScope like so:
myApp.directive('gScope', function(){
return {
restrict: 'A',
replace: false,
transclude: false,
controller: "DirectiveCntl",
link: function(scope, element, attrs, controller) {
controller.saveScope(attrs.gScope);
}
}
});
...
function DirectiveCntl($scope, $rootScope) {
this.saveScope = function(id) {
if($rootScope.directiveScope == undefined) {
$rootScope.directiveScope = [];
}
$rootScope.directiveScope[id] = $scope;
};
}
...
<span>Now I can access the message here: {{directiveScope['myScopeId'].message}}</span>
<other-directive>
<other-directive g-scope="myScopeId" ng-model="message"></other-directive>
</other-directive>
Note: While this makes it a snap to collect data from all your various directives it comes with my word of caution that now you have to ensure the potential pile of scopes are properly managed to avoid causing a memory leak on pages. Especially if you are using the ng-view to create a one page app.