[英]AngularJS - Update controller var on route change
I'm pretty much a newbie in the AngularJS world. 我几乎是AngularJS世界中的新手。 This is my problem.
这是我的问题。 I would like to update the selected tab based on the url, so that the selected tab changes when the url changes.
我想根据url更新所选标签,以便在url更改时更改所选标签。
This is my js: 这是我的js:
app.config(function($routeProvider, $locationProvider){
$routeProvider
.when('/page1', {
templateUrl: '/views/pages/page1.html',
controller: "TabController",
tab: 1
})
.when('/page2', {
templateUrl: '/views/pages/page2.html',
controller: "TabController",
tab: 2
})
.otherwise({
template: "Error 404"
});
$locationProvider.html5Mode({enabled: true, requireBase: false});
});
//Tabs
app.controller("TabController", function($scope, $route){
$scope.activeTab = 0;
if(typeof $route.current != "undefined"){
setTimeout(function(){$scope.activeTab = $route.current.activeTab; console.log($scope.activeTab);},100);
}
});
And this is my html: 这是我的html:
<div ng-controller="TabController">
<!-- Tabs -->
<section class="section section--xs">
<div class="container">
<div class="tab">
<div class="tab__single" ng-class="{active: activeTab === 1}">
<a href="/page1" class="tab__single__name">Page 1</a>
</div>
<div class="tab__single" ng-class="{active: activeTab === 2}">
<a href="/page2" class="tab__single__name">Page 2</a>
</div>
</div>
</div>
</section>
<!-- ./tabs -->
<!-- Content -->
<ng-view></ng-view>
<!-- ./content -->
</div>
I try and if I log the tab value, it actually updates, because it logs the correct value, but then the new tab doesn't get selected. 我尝试,如果我记录了选项卡的值,它实际上会更新,因为它记录了正确的值,但是新的选项卡没有被选中。 Any suggestions?
有什么建议么?
You could create a function to search in your url parameters: 您可以创建一个函数来搜索url参数:
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
HTML: HTML:
<div class="tab">
<div class="tab__single" ng-class="{active: isActive('page1')}">
<a href="/page1" class="tab__single__name">Page 1</a>
</div>
<div class="tab__single" ng-class="{active: isActive('page2')}">
<a href="/page2" class="tab__single__name">Page 2</a>
</div>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.