简体   繁体   English

$ router未绑定$ Angular 1.5组件

[英]$router is not bound in Angular 1.5 component

I'm playing around with Angular 1.5 components and am struggling to get the $router bound by the framework. 我正在玩Angular 1.5组件,并且很难让$ router受到框架的限制。

Basically I want to navigate from one component to another programatically - hence the need of using the $router. 基本上我想以编程方式从一个组件导航到另一个组件 - 因此需要使用$ router。

The only thing I have in my index.html is a ng-outlet: 我在index.html中唯一拥有的是ng-outlet:

<ng-outlet></ng-outlet>

Then I have this mapping: 然后我有这个映射:

.component('webGuiComponent', {
  template: '<ng-outlet></ng-outlet>',
  $routeConfig: [
    { path: '/welcome/...', name: 'Welcome', component: 'welcomeComponent', useAsDefault: true },
    { path: '/timeline/...', name: 'Timeline', component: 'timelineComponent' }
  ]
})

Notice it will call on the Welcome Component, which is mapped like this: 请注意,它将调用Welcome Component,它的映射方式如下:

.component('welcomeComponent', {
  template: '<visitant-header $router="$$router"></visitant-header><div class="container"><ng-outlet></ng-outlet></div>',
  $routeConfig: [
    { path: '/', name: 'Index', component: 'indexComponent', useAsDefault: true },
    { path: '/newUser', name: 'NewUser', component: 'newUser' }
  ]
})

.component('indexComponent', {
  templateUrl: '/app/components/welcome/index.html'
});

That's where I try to bind the $router: visitant-header $router="$$router" . 这就是我尝试绑定$ router的地方: visitant-header $ router =“$$ router”

The visitant header component and controller is defined as such: 访问者头部组件和控制器定义如下:

.component('visitantHeader', {
  templateUrl: '/app/components/shared/headers/vistantHeader.html',
  bindings: { $router: '<' },
  controller: 'visitantHeaderController'
})

.controller('visitantHeaderController', ["$scope", "$location", function ($scope, $location) {

  var $ctrl = this;

  this.goTo = dest => { this.$router.navigate(dest); }

}]);

When the goTo function is called, the following error is thrown: 调用goTo函数时,抛出以下错误:

angular.js:13550 TypeError: Cannot read property 'navigate' of undefined
    at goTo.dest [as goTo] (visitantHeaderController.js:7)
    at fn (eval at <anonymous> (angular.js:14432), <anonymous>:4:315)
    at b (angular.js:15485)
    at e (angular.js:25018)
    at n.$eval (angular.js:17229)
    at n.$apply (angular.js:17329)
    at HTMLButtonElement.<anonymous> (angular.js:25023)
    at Qf (angular.js:3456)
    at HTMLButtonElement.Pf.d (angular.js:3444)

Ie $router wasn't bound. 即路由器没有绑定。

Any clue as to why? 任何线索为什么?

You can do this thing in other child components but it would not work inside root component(don't know the exact reason). 您可以在其他子组件中执行此操作,但它在根组件内不起作用(不知道确切原因)。 Inject $rootRouter inside the controller and try $rootRouter.navigate(['Dest']); 在控制器内部注入$ rootRouter并尝试$ rootRouter.navigate(['Dest']); It worked for me. 它对我有用。

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

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