I am using AngularJS with the alias controllers pattern. I can\'t access (or I don\'t know how to) directive methods from a parent controller.
I have a
After trying both the $broadcast
and the control
object solutions, I would actually recommend trying to bind values or arrays. The control
object is a simple way to achieve the desired result, but in my testing very undiscoverable and error-prone.
This Codepen builds BernardV's example, but uses an array of messages as a very visible control binding. If you want, you can easily $watch
the messages array inside the directive as well. The core idea is to in the directive use:
scope: { messages: "=", room: "@" },
From a controller (having an array of "rooms") you would do this:
$scope.addMessages = function () {
angular.forEach($scope.rooms, function(room, index) {
room.messages.push("A new message! # " + (index+1);
})
}
Independent directives, independent messages and highly discoverable. You could of course in the directive only show the latest message, or simply bind a string instead of an array. This solution worked much better for us at least.