Ui-sref不生成可点击链接/不工作

时间:2014-12-21 21:42:48

标签: angularjs angular-ui-router

之前我使用了ng-route并且工作正常,但是使用UI路由器,链接不再可点击,或者至少大部分时间它们都不可点击。当它们非常随机时,它们不会显示我正在使用的html模板。

HTML:

<head>
    <title>Tutorial</title>

    <script src="lib/angular/angular.js"></script>
    <script src="lib/angular/angular-ui-router.min.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>

</head>

<body>

   <ng-view></ng-view>

    <ul class="menu">
        <li><a ui-sref="view1">view1</a></li>
        <li><a ui-sref="view2">view2</a></li>
    </ul>

的.js

angular.module('myApp', [
    'myApp.controllers',
    'ui.router'
    ]);

angular.module('myApp').config(function($stateProvider, $urlRouterProvider) {

    $stateProvider.state('view1',{
        url: '/view1',
        controller:'Controller1',
        templateUrl:'/view1.html' 
    }).state('view2', {
        url: '/view2/:firstname/:lastname',
        controller: 'Controller2',
        resolve: {
            names: function() {
                return ['Misko', 'Vojta', 'Brad'];
            }
        },
        templateUrl: '/view2.html'
    });

    $urlRouterProvider.otherwise('/view1');

});


angular.module('myApp.controllers', []).controller('Controller1', function($scope, $location, $state) {

    $scope.loadView2=function() {
        $state.go('view2', {
            firstname: $scope.firstname,
            lastname: $scope.lastname
        });
    };
}).controller('Controller2', function($scope, $stateParams, names) {
    $scope.firstname = $stateParams.firstname;
    $scope.lastname = $stateParams.lastname;
    $scope.names = names;

});

我按照AngularJS上的SitePoint电子书中的说明进行操作,因此我不确定我做错了什么或我错过了什么。

http://plnkr.co/edit/amh3nZmyB7lC2IQi3DIn

2 个答案:

答案 0 :(得分:9)

我在标记中的任何位置都没有看到ui-view,因此您的州的观点很可能不会被渲染和注入。

您不应该需要ng-view。主HTML文件中应存在单个ui-view。您的顶级状态将被渲染并注入其中。状态可以有子状态,并且具有子状态的状态的每个模板应该具有其自己的ui-view,其中将呈现其呈现的子状态。

查看ui-router's readme了解其运行的基础知识。此外,它们有一个很好的demo app,其来源确实帮助我理解了这个状态路由引擎的用途以及如何使用它。

答案 1 :(得分:4)

Helpful info, hopefully...

Although the answers above are correct (missing ui-view, referencing ui.router, etc.), I have run into situations where other problems with the load of a view will cause links to not be generated. For example, this morning I forgot to reference the module angular-cache and was running into a problem with CacheFactory not loading (completely unrelated to ui.router). Until the references were resolved, ui.router was dead in the water.