我有一個下拉菜單,其中包含頁面各個部分的一些鏈接。該應用程序使用AngularJS 1.4版編寫,下拉菜單可以使用,但是當我通過下拉菜單中的url直接進入頁面時,總是選擇空的聲音而不是正確的聲音。這裏的代碼:AngularJS根據網址選擇默認選項
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'
}
];
如果我選擇在下拉菜單中選擇聲音,我去與選擇正確的聲音正確的鏈接。但如果在url欄中輸入如下內容:
www.myapp.com/account/billing
我轉到正確的頁面,但在下拉菜單中所選語音爲空。
我該如何解決這個問題?第一次答覆後
編輯:
我加了這一點:
Object {name: "Design", url: "account.design"}
:
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);
我得到正確的對象,例如打印
在html我si mply添加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>
但沒有任何改變。
你能給我們一個簡短的例子嗎? – Nico
短樣本是什麼意思? – ste