gpt4 book ai didi

javascript - 根据 routeProvider 更改值

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:58:33 25 4
gpt4 key购买 nike

 var mainApp = angular.module("mainApp", ['ngRoute']);

mainApp.controller('myCtrl', function($scope) {
$scope.tab = 3;

});



mainApp.config(function($routeProvider) {
$routeProvider
.when('/cc', {
templateUrl: 'cc.html',
})
.when('/pl', {
templateUrl: 'pl.html',
})

我正在使用路由根据用户选择显示不同的页面。我正在使用 ng-class 在用户单击该链接后更改所选页面链接的外观。ng-class 取决于 Controller 中设置的变量 tab 的值。

问题 - 当我重新加载页面 www.foo.com/pl 时, View 显示 pl.html 但 tab 的值重置为 3。从而使其他链接处于事件状态而不是“pl”。

我希望 tab 的值根据正在加载的页面而改变(即使我刷新该值也应该相应地改变)。我怎样才能做到这一点?任何帮助将不胜感激。

最佳答案

你应该为每个路由添加一个参数:

mainApp.config(function($routeProvider) {
$routeProvider
.when('/cc', {
templateUrl: 'cc.html',
selected: 1
})
.when('/pl', {
templateUrl: 'pl.html',
selected: 2
})

然后将$route注入(inject) Controller :

mainApp.controller('myCtrl', function($scope, $route) {
$scope.tab = $route.current.selected;
});

并使用 ng-class 指令在 html 中进行验证:

<a href="/cc" ng-class="{active: tab == 1}">link1</li>
<a href="/pl" ng-class="{active: tab == 2}">link2</li>

另一种方式是使用$location服务。

mainApp.controller('myCtrl', function($scope, $location) {
$scope.tab = $location.path();
});

HTML:

<a href="/cc" ng-class="{active: tab == '/cc/'}">link1</li>
<a href="/pl" ng-class="{active: tab == '/pl/'}">link2</li>

关于javascript - 根据 routeProvider 更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33810284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com