javascript 动态改变href angular JS的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24365840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:39:20  来源:igfitidea点击:

dynamically change the path of href angular JS

javascriptjqueryangularjsangularjs-directive

提问by user1853128

I am trying to change the href value on click of it.

我试图在点击它时更改 href 值。

This is what I have tried.

这是我尝试过的。

HTML:

HTML:

<a href="#Page1">Demo</a>

JS:

JS:

    angular.config(function ($routeProvider) {
        $routeProvider
    .when('/Page1', {
            templateUrl: 'main.html'
            controller: 'FirstController'
        })
 .when('/Page2', {
            templateUrl: 'sub.html'
            controller: 'FirstController'
        })
.otherwise('main.html');

How do I change the path of the anchor tag everytime when I clicked on it.

每次单击时如何更改锚标记的路径。

Can anyone please help me out.

任何人都可以帮助我。

回答by s.alem

Use different controllers for each page. You can use a variable for link and set it in the related controller. For example:

为每个页面使用不同的控制器。您可以使用链接变量并将其设置在相关控制器中。例如:

<a href="#/{{myLink}}">Demo</a>

or

或者

<a ng-href="#/{{myLink}}">Demo</a>

And in the each related controller:

在每个相关的控制器中:

$scope.myLink="page1";

or

或者

$scope.myLink="page2";

etc.

等等。

Or if you insist to use same controller, you can check the location path:

或者,如果您坚持使用相同的控制器,您可以检查位置路径:

if ($location.path().substring(1) == "page1") {
    $scope.myLink="page2";
}

回答by btk

Use ng-hrefinstead - it will automatically update when the bound value changes.

ng-href改为使用- 它会在绑定值更改时自动更新。