How to add a class from toggleClass
directive to Header
directive without using a jQuery selector? Not sure how I can do this in AngularJS, is directive to directive communication needed in this case?
<Header></Header>
<toggleClass></toggleClass>
in toggleClass directive I have:
module.exports = Directive;
function Directive(){
return {
restrict: 'E',
templateUrl: '/directive.html',
link : function(scope, element){
scope.expandToggle = function() {
// add class to Header directive
}
}
}
};
and its template:
<div ng-click="expandToggle()">
<span class="collapseText">Collapse</span>
<span class="expandText">Expand</span>
</div>
You can $emit
event from toggleClass
directive to parent controller, and change boolean value to control adding/removing your class.
ToggleClass directive:
module.exports = Directive;
function Directive(){
return {
restrict: 'E',
templateUrl: '/vic-compare-quotes-expand/templates/directive.html',
link : function(scope, element){
scope.expandToggle = function() {
scope.$emit('toggle');
}
}
}
};
Parent controller:
angular
.module('yourModule')
.controller('YourController', ['$scope', YourController]);
function YourController($scope) {
$scope.$on('toggle', function() {
$scope.apllyNeededClass = true;
})
}
Your HTML:
<Header ng-class="{'classToApply': apllyNeededClass}"></Header>
<toggleClass></toggleClass>
You can use services for sharing data between controllers (directive and controller in your case).
ToggleClass directive:
module.exports = Directive;
function Directive(){
return {
restrict: 'E',
templateUrl: '/vic-compare-quotes-expand/templates/directive.html',
link : function(scope, element){
scope.expandToggle = function() {
yourService.apllyNeededClass = true;
// don't forget to inject "yourService" in this directive
}
}
}
};
Parent controller:
angular
.module('yourModule')
.controller('YourController', ['$scope', 'yourService', YourController]);
function YourController($scope, yourService) {
$scope.apllyNeededClass = yourService.apllyNeededClass;
// bind service variable to your $scope variable
}
Your HTML:
<Header ng-class="{'classToApply': apllyNeededClass}"></Header>
<toggleClass></toggleClass>
I'm using ng-class
on <Header>
tag just for example and because I don't know the template of your Header
directive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.