javascript - Angularjs $stateChangeStart 检查字符串是否在对象中

标签 javascript angularjs angular-ui-router

我的 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) {...}

在我的 $rootScope.$on('$stateChangeStart') 中,我想检查我的 toState.name 是否等于任何 窗口。 audience.Config.somePage.routerName window.audienceConfigconsole.log() 输出如下:

"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"
    ]
}

我需要验证每次更改路由时 toState.name 是否等于上述对象的任何 routerName 属性,有没有办法这在 if 中?

最佳答案

我其实知道两种方法:

第一个,我见过很多人不喜欢它,但它包括检查您的州名称是否存在于您的州。将其添加到 $stateChangeStart 事件函数中;您可以使用以下代码实现它。例如,如果你想检查你是否要去仪表板。

if (toState.name.indexOf('dashboard') > -1  ) {
            //do something. 
        }

实现它的第二种方法是使用我认为属于ui-router 的 native $state,以防你使用那个库,或者任何你用于改变状态。

$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
    }
}

第二种方法需要更多逻辑,但在我看来,它更简洁。

关于javascript - Angularjs $stateChangeStart 检查字符串是否在对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297964/

相关文章:

javascript - Angularjs 和 Intel XDK 不能很好地混合

java 和 jsp_session expired_redirect

javascript - Angular UI-Router 多个菜单(顶部水平和左侧垂直菜单)

javascript - Angular : $scope works but "controller as" does not fire ng-change event

javascript - 如何使用 angularJS 从 JSON url 获取数据

javascript - 如何设置 Angular ui-router 状态,以便主模板不会在每次状态更改时刷新?

php - 无法获取值(value)

javascript - Mocha/节点 : how to use assert. 拒绝()?

html - 尝试在 html 模板中显示 GIF 时引发错误

javascript - Highcharts - 动态启用/禁用滚动条