Issue
I have the following code inside my app.run()
:
window.audienceConfig = InstitutionConfiguration.checkConfiguration(INSTITUTION_URL).then( response => {
window.audienceConfig = response.institution.landing_configuration;
console.log(window.audienceConfig);
});
$rootScope.$on('$stateChangeStart', function(event, toState) {...}
Inside my $rootScope.$on('$stateChangeStart')
I want to check if my toState.name
is equal to any of the window.audience.Config.somePage.routerName
The console.log()
of window.audienceConfig
outputs the following:
"dashboard": {
"routerName": "basicLayout.dashboard",
"audience": [
"faculty",
"student",
"employee"
]
},
"profile": {
"routerName": "basicLayout.content",
"audience": [
"faculty",
"student"
]
},
"academic_resources": {
"routerName": "basicLayout.academicResources",
"audience": [
"student"
]
},
"university_services": {
"routerName": "basicLayout.universityServices",
"audience": [
"student"
]
},
"support_center": {
"routerName": "basicLayout.supportCenter",
"audience": [
"student",
"faculty",
"employee"
]
},
"progress_coach": {
"routerName": "basicLayout.progressCoach",
"audience": [
"student"
]
}
I need to verify if every time I change route, toState.name
is equal to any of the routerName
properties of the object above, is there a way to do this inside an if?
Solution
I actually know two ways of doing so:
The first one , I´ve seen many people who don´t like it, but it consists on checking if the name of your state exists on your state. Add it within $stateChangeStart
event function ;you achieve it with the following piece of code. For example if you want to check if you are going to dashboard.
if (toState.name.indexOf('dashboard') > -1 ) {
//do something.
}
The second way to achieve it is by using the native $state which I think belongs to ui-router, in case you are using that library, or any you are using for changing the states.
$rootScope.$on('$stateChangeStart', function(event, toState) {...
var stateName = $state.name;
console.log(stateName)
console.log(toState)
//Check your console because stateName and toState are formated as an
//object or smth like that.
//You need to read and extract the first element of the array with a
//foreach. After that, you may use the real name from the state and compare
if (stateNameExtracted === toStateExtracted){
//do Something
}
}
The second approach requires more logic, but in my opinion, it´s cleaner.
Answered By – eduardo92
Answer Checked By – Senaida (AngularFixing Volunteer)