I'm new to AngularJS and need some help. I have two directives (parent and child). When I click a link, the parent directive will fire a broadcast event that the child directive is listening for. Mainly I can't get the broadcast listener to capture the broadcasted event when it is fired. Here is my code so far:
<div all-checkboxes-broadcast>
<a href="" ng-click="checkAll()">Select All</a>
<a href="" ng-click="clearAll()">Clear All</a>
<div all-checkboxes-listeners>
<input type="checkbox" />
</div>
</div>
AllCheckboxesBroadcast.js
"use strict";
app.directive('allCheckboxesBroadcast', function () {
return {
restrict: 'A',
controller: ['$scope',
function($scope) {
//select all checkboxes
$scope.checkAll = function () {
$scope.$broadcast('allCheckboxes',true);
};
//de-select all checkboxes
$scope.clearAll = function () {
$scope.$broadcast('allCheckboxes',false);
};
}
]
}
})
AllCheckboxesListener.js
"use strict";
app.directive('allCheckboxesListener', function () {
return {
restrict: 'A',
require: '^allCheckboxesBroadcast',
link: function() {
if ($scope.$on('allCheckboxes') == true) {
angular.forEach(element.find('input[type=checkbox]'), function(){
this.prop('checked',true);
});
}
}
}
})
Ok so a few things... The directive name must match camel cased version i.e. "allCheckboxesListeners" in your case. You have one with an "s" on the end and one without. Regarding the scope, any directive within another will automatically get the same scope unless you start specifying otherwise. So just add it as a parameter in your
link
function and it'll be the parent scope which is available. Also I would not usefind()
when using angular. Instead I would bind those checkboxes to some array of objects so you don't have to manipulate the DOM! Also unless you're using the full version of jQuery alongside, you are limited to searching by tag names in jqLite, which is what angular uses unless you have jQuery added separately (e.g. you'd be limited to searching by onlyinput
for example).See example in action here: http://plnkr.co/edit/0n1NVpAl2u8PYyPd6ygL?p=preview
JavaScript
HTML