I have an Angular 1.5 component with a controller (which uses controllerAs syntax), where I wrote a function adding additional css class to the component element if a certain html element exists in the page. If this certain html element doesn't exist, this additional css class is not applied on the component. That works in the pages where the html element which I am looking for, exists. However, when switching to another state, the component keeps the additional css class no matter that the html element doesn't exist on this state. You have to refresh the app in order to 'reset' the function which comes from the component's controller. This component is used on every page in the application.
For example, this is my component:
function myComponentController() {
activate();
function activate(){
addAdditionalCssClass();
}
function addAdditionalCssClass(){
// code for adding additional css class to the component
// if html element exists
}
}
It works fine when we are on a state where this html element exists. However when we go to another state, where the concrete html element is null
, the function addAdditionalCssClass()
continiues to add additional class to the component. Any help/suggestions would be greatly appreciated.
As I understand, you have a page with some dynamic html and a component in this page that should reflect the current state with a change in its classes.
One solution would be to have the component depend of a list of classes, i.e. have in its bindings
a classes
attribute, e.g.
.component('classSpecial', {
template: "<div ng-class='$ctrl.classes'>Hello</span></div>",
bindings: {
classes: '<'
}
})
See a simple example here, where you can change the classes of a component from the controller of the page.