【问题标题】:Angular.js : How to use ng-href in template?Angular.js:如何在模板中使用 ng-href?
【发布时间】:2014-07-11 17:41:22
【问题描述】:

我尝试使用 1 个包含模板的 index.html 创建一个简单的 SPA。

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

 <a ng-href="#/myPage">myPage</a>

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

<a href="#/myPage">myPage</a>

我的应用

index.html:

...
<body ng-app="myApp">
    <a ng-href="#/myPage" target="_self">link</a> <!-- work ! -->
    <div class="container" ng-view=""></div>
</body>
...

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 : '/'
            });
        });

controller.js

'use strict';

    myApp.controller('MainCtrl', function() {
        this.myColor = 'blue';
    });

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>

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

【问题讨论】:

    标签: javascript html angularjs templates


    【解决方案1】:

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

    <a ng-href="#/{{myPathVariable}}"/>Take Me Somewhere</a>
    

    在你的范围内:

    $scope.myPathVariable = 'path/to/somewhere';
    

    然后angular编译后是这样的:

    <a ng-href="#/path/to/somewhere" href="#/path/to/somewhere" ... other angular attributes>Take Me Somewhere</a>
    

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

    【讨论】:

    • 好的,但是为什么 link 不能在模板中工作?
    • 这行不通,因为您将 myPage 作为字符串文字而不是变量传递到属性中
    • 我建议添加空的 href 标签以确保浏览器将其作为链接选择:Take Me Somewhere
    • 嗯,ng-href 指令会为你添加和覆盖空的 href 属性,所以不需要。
    • 我有ng-href="#!/database/{{home.uuidSelectedDatabase}}/segments?{{goToSegmentsUrlQuery}}",它总是显示,不管goToSegmentsUrlQuery是否已经定义在范围内:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多