简体   繁体   English

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

[英]Angular.js : How to use ng-href in template?

I try to create a simple SPA with 1 index.html which include templates. 我尝试创建一个带有1个index.html的简单SPA,其中包含模板。

I got a problem with ng-href directive: 我遇到了ng-href指令的问题:

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

work in index.html but not in my templates, the link is unclickable. 在index.html中工作但不在我的模板中,链接是不可点击的。 but href still works. 但是href仍然有效。

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

My app : 我的应用

index.html: index.html的:

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

app.js: 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 controller.js

'use strict';

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

page.tpl.html 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>

I don't understand the problem with ng-href and why the result is different than href. 我不明白ng-href的问题以及为什么结果与href不同。 I use angular 1.2 我用角度1.2

ngHref is used to dynamically bind angular variables to the href attribute like so: ngHref用于动态地将角度变量绑定到href属性,如下所示:

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

Where in your scope: 在您的范围内:

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

Then after angular compiles it, it looks like this: 然后在角度编译后,它看起来像这样:

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

If your path is hardcoded into the page (you know where the link should take you on page load), you can just specify it in an href, which is why your third example works. 如果您的路径被硬编码到页面中(您知道链接应该在页面加载时占用的位置),您可以在href中指定它,这就是您的第三个示例有效的原因。 Only use ngHref when you need angular to decide the route dynamically after the JS loads. 只有在需要角度时才使用ngHref来在JS加载后动态决定路径。 This prevents your user from clicking links and going to an invalid route before angular has deciphered where the link should point. 这可以防止用户在角度已解密链接应指向的位置之前单击链接并转到无效路径。 Documentation here 文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM