This is my page's structure.
// app.html
<wrapper ng-if="initialized && $root.user.type!='guest'">
<header-component></header-component>
<div class="app-body">
<sidebar-component></sidebar-component>
<main class="main-content" style="height:{{$root.pageHeight}}px; overflow-y: scroll">
<ng-view></ng-view>
</main>
<aside-component></aside-component>
</div>
</wrapper>
Now in ng-view directive I have a controller which needs to pass data to the header-component.
As you can see, ng-view is not associated to header-component in some way.
Let's say that ng-view controll now screen is:
// some-screen.js
$scope.foo = "bar";
And I want to display bar in the header.
I can do this both with $rootScope (without any event) or using the $broadcast event.
First method - using the $rootScope - as it is - without just anything:
// some-screen.js
$rootScope.foo = "bar";
// header.js
app.directive("headerComponent", ($rootScope) => {
return {
templateUrl: "/structure/header/header.html",
scope: {},
link: function($scope, element, attrs) {
console.log($rootScope.foo) // "bar"
}
}
});
Second method - using the $broadcast event
// some-screen.js
$rootScope.$emit("SomeNameOfTheEvent", $scope.foo);
// header.js
app.directive("headerComponent", ($rootScope) => {
return {
templateUrl: "/structure/header/header.html",
scope: {},
link: function($scope, element, attrs) {
$rootScope.$on("SomeNameOfTheEvent", function(event, info) {
console.log(info.foo) // "bar"
});
}
}
});
Now notice two things while using the $broadcast event:
You need to specify name for this event - in big app this can be tricky - since
you probably ain't going to remember the names you throw while coding.
And sitting and think of good names is a waste of time.
You will probably need to make a documentation in order to re-use the event name from other places
in the app - otherwise you will mistakely try to use the same event but with wrong names.
They are both doing the same - $broadcast just takes more code to function.
What am I missing, AngularJS probably created the $broadcast event for something.
$emit dispatches an event upwards ... $broadcast dispatches an event
downwards
Detailed explanation
$rootScope.$emit only lets other $rootScope listeners catch it. This is good when you don't want every $scope to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them.
$rootScope.$broadcast is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it.
$scope.$emit is when you want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear).
$scope.$broadcast is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.
Related
I know if I have two directives that are nesting I can communicate throw controller, require and pass it as the fourth parameter of the link function.
<my-first-div>
<my-seconded-div></my-seconded-div>
</my-first-div>
and every thing will work fine.
but I could do the same thing when they weren't nesting.
<my-first-div></my-first-div>
<my-seconded-div></my-seconded-div>
why ?
and how do I make them communicate ?
It happens since both of the directives have watchers on the same variable reference. So the changed value is being 'noticed' in all the relevant directives.
You could mimic this "communication" by passing the same variable (By Reference) (varName:'=') for both directives and place watchers on that variable inside each of these directives.
Then, the DOM hierarchy won't matter
For example:
Directive 1:
app.directive('directive1', function () {
return {
restrict: 'E',
scope: {
myVar: '='
}
link: function (scope, element, attrs) {
// do something with main directive
console.log("directive1", scope.myVar);
$scope.$watch("scope.myVar", function (value) {
console.log("directive1", "value changed to:" + scope.myVar)
});
}
}
});
The same for the second directive..
For both directives pass the same variable
And the magic will happen
I assume by saying communicating, you mean sharing data, state and events between two directives. I will list basic ways that I have in mind here:
The reason why you can pass data/state between two nested directives is because in AngularJS a child directive (nested one in your example) inherits the scope of it parents. As the results, two sibling directives can share same data from its parent controller.
<div ng-controller="ParentCtrl">
<ng-sibling></ng-sibling>
<ng-another-sibling></ng-another-sibling>
</div>
In the above piece of code, ng-sibling and ng-another-sibling will inherit the same data that is defined in their parent ParentCtrl
AngularJS support emitting/broadcasting event/data using $broadcast, $emit and $on function, document can be found here: https://docs.angularjs.org/api/ng/type/$rootScope.Scope.
$emit can be used to sent event upward the tree's hierarchy, while $broadcast's downward, and the direction is essential.
So one of your directive can dispatch the event, while the other listen to it. It's pretty similar to the way jQuery trigger events.
// In link function or controller of one directive
$scope.$broadcast("EVENT_A",my_data);
// Listen to EVENT_A on another directive
$scope.$on("EVENT_A",function($event,data){
....
})
While two-way binding or firing event arbitrarily can be useful at first, they can also lead to the situation when it's really difficult to keep track of the application's event and data flow. If you find this situation, maybe consider using Flux architecture with AngularJS not a bad idea. Redux fully supports AngularJS and all of your directives can be built as single-state components. The Github repo can be found here: https://github.com/angular-redux/ng-redux, and a simple tutorial on how to run AngularJS with Redux can be found here: http://blog.grossman.io/angular-1-using-redux-architecture/
I'm building a growl like UI in angular. I'd like to expose it as a factory (or service) to make it available in my controllers. Calling growl.add will result in a change in the DOM, so it seems like I should have a directive take care of that, rather than doing direct DOM manipulation in the factory. Assuming that a factory-directive combo is the best option (and please correct me if that is not a good assumption), the question is:
How best to communicate between the factory and the directive?
Specifically, how best to send messages from the factory to the directive? Other questions have well covered sending information the other way, with onetime callback.
See below the working example. I suspect there is a better way though..
For reference, I have played with other options:
A) have the directive watch the service, e.g.
$scope.$watch(function(){
growl.someFunctionThatGetsNewData()},
function(newValue){
//update scope
})
But this means that someFunctionThatGetsNewData gets called in every digest cycle, which seem wasteful, since we know that the data only gets changed on growl.add
B) send an 'event', either via routescope, or via event bindings on the dom/window. Seem un-angular
Since neither of those options seem good, I'm using the one below, but it still feels hacky. The register function means that the directive and the factory are tightly coupled. But then again from usage perspective they are tightly bound - one is no good w/o the other.
It seem like the ideal solution would involve declaring a factory (or service) that includes the directive in its declaration (and perhaps functional scope) so that it exposes a single public interface. It seems icky to have two separate publicly declared components that entirely depend on each other, and which have tight coupling in the interfaces.
Working example - but there must be a better way..
vpModule.directive('vpGrowl',['$timeout', 'growl', function ($timeout, growl) {
return {
template: '<div>[[msg]]</div.',
link: function($scope, elm, attrs) {
growl.register(function(){
$scope.msg = growl.msg;
});
$scope.msg = growl.msg;
}
};
}]);
vpModule.factory('growl', ['$rootScope', '$sce', function($rootScope, $sce) {
var growl = {};
growl.msg = '';
var updateCallback = function(){};
growl.add = function(msg){
growl.msg = msg;
updateCallback();
};
growl.register = function(callback){
updateCallback = callback;
};
return growl;
}]);
I would have your growl service decide what to show, not the directive. So, the service handles any timers, state, etc. to decide when to hide/show messages. The service then exposes a collection of messages which the directive simply binds to.
The directive can inject the service and simply place it in scope, and then bind an ng-repeat to the service's collection. Yes, this does involve a watch, but you really don't need to worry about the performance of a single watch like this.
link: function(scope, elm, attrs) {
scope.growl = growl; // where 'growl' is the injected service
}
and then in the directive template:
<div ng-repeat="msg in growl.messages">
...
</div>
I would implement following logic:
Service growl defines some property growlProp on $rootScope & update it on each call of growl.add
Directive set watcher on $rootScope.growlProp
So directive knows nothing about service & service knows nothing about directve.
And additional overhead related to watcher is minimum.
I have a custom directive that I'm using in my templates. It does a bit of DOM work for me. I would like the host view/controller that I'm using the directive in to be able to run methods on my directive (and it's controller). But I'm not sure how best to call into the directives scope.
Example Fiddle
My view code:
<div ng-app="app">
<div ng-controller="MainCtrl">
<h3>Test App</h3>
<button ng-click="scopeClear()">Parent Clear</button>
<div my-directive string="myString"></div>
</div>
</div>
Here is the custom directive:
angular.module('components', []).directive('myDirective', function() {
function link(scope, element, attrs) {
scope.string = "";
scope.$watch(attrs.string, function(value) {
scope.string = value;
});
}
return {
controller: function($scope, $element) {
$scope.reset = function() {
$scope.string = "Hello";
}
$scope.clear = function() {
$scope.string = "";
}
},
template:
"<button ng-click='reset()'>Directive Reset</button>" +
"<button ng-click='clear()'>Directive Clear</button><br/>" +
"<input type='text' ng-model='string'>",
link: link
}
});
And controller:
angular.module('app', ['components']).controller('MainCtrl', function($scope) {
$scope.myString = "Hello";
$scope.scopeClear = function() {
// How do I get this to call the clear() method on myDirective
}
});
The workaround I found is jQuery('#my_directive').scope().myMethod(); But this seems wrong, like I'm missing some better part of angular to do this.
It also seems like and $emit isn't right here since I want a targeted method so it won't trigger on additional instances of the directive I have on the same page.
How would I access the directives methods from my parent controller?
I'm not sure I fully understand your objective here, and it's possible you could find a better pattern completely. Typically, directives display the state of the scope which is either an isolate scope (if they are self-sufficient) or a shared scope. Since you are not creating an isolate scope then they inherit the scope from the controller. If they are displaying data inherited from the controller then you don't want your controller calling into the directive, rather the directive will simply "redraw" itself whenever the properties in the controller change.
If you, instead, are looking to recalculate some stuff in your directives based on events from outside the directive you don't want any tight coupling - especially if building an entirely separate module. In that case, you might simply want to use $broadcast from the $scope within MainCtrl to broadcast an event that you may care about, and then your directive can provide the $on('eventName') handler. This way it's portable to any controller/scope that will fire such an event.
If you find yourself needing to know the exact properties in the controller or the exact functions within the directive then I would suggest that you have too-tightly coupled these pieces and they don't belong in separate modules since they could never be reused. Angular directives and controllers are not objects with functions, but objects that create scope and update frequently via $digest calls whenever properties in that scope change. So you may be able to find a way to better model the data, objects, and properties you are displaying. But I can't say without greater context.
I have a directive that broadcasts an event when a table row gets clicked. Here is the directive:
angular.module('app').directive('encounterItemTable', function () {
return {
restrict: 'A',
replace: true,
templateUrl: 'views/encounter.item.table.html',
scope: {
encounters : '='
},
link: function(scope) {
scope.getSelectedRow = function(index) {
scope.$broadcast('selectedRow', { rowIndex: index });
};
}
};
});
Here is the markup that calls the getSelectedRow
<tr ng-class="{selected: $index==selectedIndex}" ng-repeat="encounter in encounters | filter:search" data-id="{{encounter.id}}" ng-click="getSelectedRow($index)">
My getSelectedRow() function gets called when the row gets clicked. The index is correct. The controller on the other hand never hears anything. Here is the code in the controller.
$scope.$on('selectedRow', function(event, data) {
$scope.selectedIndex = data.rowIndex;
$scope.selectedEncounter = $scope.encounters[data.rowIndex];
});
Why would the controller not hear the event? What am I missing?
I use $rootScope.$broadcast(event, data). I use events to decouple components i.e. components emitting events and listeners for events don't need to know about each other.
In your case where the event could reasonably contained to the component (directive) then you have to care about where in the DOM the relative positions of the listener/emitter are. I haven't run into this myself so generally use $rootScope.$broadcast() another benefit being any component in the app can listen to these events so something in a sidebar could update in relation to the events from the table (which probably not be in the same DOM hierarchy)
It is $rootScope.$broadcast. If it were to broadcast only to the current scope, your controller wouldn't see it.
$broadcast sends events down to children. directive is nested within controller so need to send event up to a parent. Use scope.$emit to push events up through parents. Read the section in scope docs titled Scope Events Propagation
I'm writing a directive which creates an mp3/audio player. The issue is that you can have many audio players in one page. What I would like to do is when one is playing and you start an other, that the one currently playing pauses. How can I achieve this with angular directives?
Thanks in advance!
Make a service that each directive uses and hold the state in there.
Something like this:
angular.module('MyPlayer' [])
.factory('playerState', function() {
var players = [];
return {
registerPlayer: function(player) {
players.add(player);
},
unregisterPlayer: function(player) {
var i = players.indexOf(player);
(i>-1) && players.splice(i,1);
},
stopAllPlayers: function() {
for(var i=0;i<players.length;i++) {
players[i].stop();
}
}
}
})
.directive('player', function(playerState) {
return {
...
link: function(scope, elem, attr) {
var player = {
stop: function() {
/* logic to stop playing */
},
play = function(song) {
playerState.stopAllPlayers();
/* logic to start playing */
}
}
playerState.registerPlayer(player);
scope.$on("$destroy", function() {
playerState.unregister(player);
});
scope.play = player.play;
scope.stop = player.stop;
...
}
}
})
Just to make the answers complete, next to broadcasting events, and exposing a service, you can also use directive controllers. These controllers are set through the controller property of a directive definition object and are shared between directives that require the same controller. This means you can have one controller for all the media players, where you can implement the logic you mentioned. See the documentation on directives (search for controller:) for more information.
I would recommend the service approach if you think there will be more consumers of the logic, or the directive controller approach if only the directives consume the logic. I would advise against broadcasting events on the root scope because of the uncoupled and global nature of it. Just my two cents! HTH
How are your directives setup? Please provide some code.
This depends on the scope of your directives, I'm going to assume a child scope. To communicate between the directives, when a user clicked to start a player, I would call a $scope.$parent.$broadcast() - or $rootScope.$broadcast() if the directives are in different controllers or using isolated scopes, but then you need to inject $rootScope into your directive - to send an event to all child scopes. My directives would be watching for this event using $on and any players that were playing would stop. After this broadcast the player clicked would start.
$broadcast() and $on() scope documentation
You can also do $rootScope.$broadcast events like playerStarted. This event can be subscribed by all directives and they can react to this event by stopping themselves. The one thing that you need to do would be pass in the data about the player which is starting so that the new player does not stop itself as it too would subscribe to such event.