我有一个下拉菜单,其中包含页面各个部分的链接。该应用程序是使用AngularJS 1.4版编写的,下拉菜单确实有效,但是当我直接通过下拉菜单中的url进入页面时,总是选择空语音而不是正确的语音。这里'代码:
HTML
<select ng-options="menu_voice.name for menu_voice in menu_voices track by menu_voice.url" ng-model='selectedOption' ng-change="changeLink()">
</select>
JS:
$scope.changeLink = function(){
$state.go($scope.selectedOption.url);
};
$scope.menu_voices = [
{
"url": 'account.company',
"name": 'Company'
},
{
"url": 'account.billing',
"name": 'Billing'
},
{
"url": 'account.password',
"name": 'Password'
},
{
"url": 'account.design',
"name": 'Design'
},
{
"url": 'account.social',
"name": 'Social'
},
{
"url": 'account.notifications',
"name": 'Notifications'
}
];
如果我在下拉菜单中选择了一个语音,我会选择正确的语音转到正确的链接。但如果在网址栏中我输入的内容如下:
www.myapp.com/account/billing
我转到了正确的页面,但在下拉菜单中,所选语音为空。
我该如何解决这个问题?
第一次回复后编辑:
我补充说:
var name = $window.location.pathname;
name = name.substring(9);
name = name.charAt(0).toUpperCase() + name.slice(1);
var url = $window.location.pathname.substring(1).replace(/\//g, '.');
$scope.getSelectedFromUrl = function(){
$scope.selectedOption = {"name": name, "url": url};
};
如果我在控制台中打印
console.log($scope.selectedOption);
我得到了正确的对象,例如:
Object {name: "Design", url: "account.design"}
在html中我只添加了ng-init:
<select ng-options="menu_voice.name for menu_voice in menu_voices track by menu_voice.url" ng-model='selectedOption' ng-change="changeLink()" ng-init="selectedOption = getSelectedFromUrl()">
</select>
但没有改变。
答案 0 :(得分:1)
您可以使用ng-init指令调用解析路径的函数,并将其与voices数组中的项匹配。然后将selectedOption模型设置为该数组项,这将设置选择选项。
ng-init="selectedOption = getSelectedFromURL()"