Angularjs 和动态路由

Angularjs and dynamic routes

我正在尝试通过以下方式在我的模板 angularjs 中创建一个 link:

 <a ng-href="/#!/content/[[value.id]]">[[key]]</a>

但我想知道是否可以做一些像 symfony2 那样的事情,例如:

routing.yml

  home_redirect:
    path: /
    defaults:
        _controller: FrontendBundle:Controller:function
        path: /home
        permanent: true
    options:
        expose: true

并通过以下操作在您的树枝模板中使用它:

<a href="{{ path('home_redirect')}}"> one link to home </a>

这真的非常有用,因为我不必 "hardcode" 我的所有路线。

你可以这样做:

'use strict';

angular.module('AngularModule')
    .config(function ($stateProvider) {
        $stateProvider
            .state('YourStateName', {
                url: '/your/url',
                views: {
                    'aViewName': {
                        templateUrl:'views/components/templates/yourTemplate.html',
                        controller: 'YourController'
                    }
                },
                resolve: {

                }
            });
    });


// then in your controller

angular.module('AngularModule')
.controller('MyController',function($scope, $state){
$scope.goTo = function(){
$state.go('YourStateName');
}
}

);

//in your html make sure the <a> tag is in scope with the 'MyController'

<a ng-click='goTo'>[[key]]</a>

你可以这样做:

<a ng-href="/your/url"></a>

这样你就可以绕过控制器,你仍然可以将逻辑放入状态中指定的控制器中

为确保路由正确,您可以使用 ui-router。

这里有一个关于 plunker

的例子

这是如何工作的:

1 - 按照他们的 github

安装 guide

2 - 写下你的状态定义:

app.config(function($stateProvider, $urlRouterProvider){
  //If no route match, you'll go to /index
  $urlRouterProvider.otherwise('/index');

  //my index state
  $stateProvider
  .state('index', {
    url: '/index',
    templateUrl: 'index2.html',
    controller: 'IndexCtrl'
  })

  //the variable state depending on an url element
  .state('hello', {
    //you will be able to get name with $stateParams.name
    url: '/hello/:name',
    templateUrl: 'hello.html',
    controller: 'HelloCtrl'
  })  
});  

3 - 按州名称编写链接:

//add this directive to an html element
//This will go to /index
ui-sref="index"
//This will go to /hello/
ui-sref="hello"
//This will go to /hello/ben
ui-sref="hello({name:'ben'})"
//This will go to /hello/{myname}
ui-sref="hello({name:myname})"

4 - 将参数放入您的控制器中:

//inject $stateParams
app.controller('HelloCtrl', function($scope, $stateParams){
  $scope.controller = "IndexCtrl";
  //get the param name like this
  $scope.name = $stateParams.name;
});

希望对您有所帮助。还要记住 ui-router 有一些非常强大的工具,例如 resolve 和 nested state/view。您现在或以后可能会需要这些论文。

PS : 如果 plunker 不工作,只需 fork 并再次保存。