Angular-Ui對於angular開發者來說是一個非常重要的工具,其中ui-router又是重中之重。然今天發現裏面的sref不支持動態綁定。
具體來說:
<a ui-sref="homePage">Home</a>
這是一個非常簡單的ui-sref的使用,當javascript重新生成網頁時,它會查找$state中名爲“homePage”的state,讀取這個state的url,然後在a標籤裏生成href="url"。
但如果,你在創建一個導航控制器,裏面有一個導航item的數組:
$scope.items = [
{name: "Home", statePage: "homePage"},
{name: "About Me", statePage: "aboutMePage"}
]
然後在html中使用repeat:
<li repeat="item in items">
<a sref="{{item.statePage}}"><{{item.name}}</a>
</li>
看起來很理所當然,而事實卻是,sref不支持動態綁定,這樣的代碼會報錯。sref中你只能使用state名,頂多加點參數。
github上已有人提交這個問題,https://github.com/angular-ui/ui-router/issues/395,但似乎是編寫者本身不希望有這樣的用法。這樣的話,你只能放棄sref,用回href綁定,你可以用$state.href來讀取state的url。