Angular.js:如何在模板中使用ng-href?

Tho*_*mas 27 html javascript templates angularjs

我尝试创建一个带有1个index.html的简单SPA,其中包含模板.

我遇到了ng-href指令的问题:

 <a ng-href="#/myPage">myPage</a>
Run Code Online (Sandbox Code Playgroud)

在index.html中工作但不在我的模板中,链接是不可点击的.但是href仍然有效.

<a href="#/myPage">myPage</a>
Run Code Online (Sandbox Code Playgroud)

我的应用:

index.html的:

...
<body ng-app="myApp">
    <a ng-href="#/myPage" target="_self">link</a> <!-- work ! -->
    <div class="container" ng-view=""></div>
</body>
...
Run Code Online (Sandbox Code Playgroud)

app.js:

'use strict';

angular.module('myApp',
        [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]).config(
        function($routeProvider) {
            $routeProvider.when('/', {
                templateUrl : 'views/main.tpl.html',
                controller : 'MainCtrl'
            })

            .when('/myPage', {
                templateUrl : 'views/page.tpl.html',
                controller : 'MainCtrl'
            })

            .otherwise({
                redirectTo : '/'
            });
        });
Run Code Online (Sandbox Code Playgroud)

controller.js

'use strict';

    myApp.controller('MainCtrl', function() {
        this.myColor = 'blue';
    });
Run Code Online (Sandbox Code Playgroud)

page.tpl.html

<div>
    <a ng-href="#/myPage" target="_self">link</a> <!-- Dont work -->
    <a ng-href="#/myPage" target="_self">link</a> <!-- Dont work -->
    <a ng-href="#/myPage{{}}">link</a> <!-- Dont work -->
    <a ng-href="#/{{ 'myPage' }}">link</a> <!-- Dont work -->
    <a href="#/myPage" target="_self">link</a> <!-- Work ! -->
</div>
Run Code Online (Sandbox Code Playgroud)

我不明白ng-href的问题以及为什么结果与href不同.我用角度1.2

Mik*_*lan 48

ngHref 用于将角度变量动态绑定到href属性,如下所示:

<a ng-href="#/{{myPathVariable}}"/>Take Me Somewhere</a>
Run Code Online (Sandbox Code Playgroud)

在您的范围内:

$scope.myPathVariable = 'path/to/somewhere';
Run Code Online (Sandbox Code Playgroud)

然后在角度编译后,它看起来像这样:

<a ng-href="#/path/to/somewhere" href="#/path/to/somewhere" ... other angular attributes>Take Me Somewhere</a>
Run Code Online (Sandbox Code Playgroud)

如果您的路径被硬编码到页面中(您知道链接应该在页面加载时占用的位置),您可以在href中指定它,这就是您的第三个示例有效的原因.仅ngHref在需要角度时才使用,以在JS加载后动态决定路径.这可以防止用户在角度已解密链接应指向的位置之前单击链接并转到无效路径.文档在这里

  • 这是行不通的,因为你将`myPage`作为字符串文字而不是变量传递给属性 (6认同)
  • 我建议添加空的href标签,以确保浏览器将其作为链接提取:<a href="" ng-href="#/{{myPathVariable}}"/> Take Me somewhere </a> (2认同)