组件路由器中的绑定 - Angular 1.5

时间:2016-04-05 12:46:45

标签: javascript angularjs ngcomponentrouter

我在组件路由器中遇到了绑定问题。

在开发人员指南中说,你应该避免在组件中使用$ scope,因此必须通过绑定传递对象。

基于以下示例: https://docs.angularjs.org/guide/componenthttps://docs.angularjs.org/guide/component-router我提出了:

HTML:

<div ng-app="app" ng-controller="MainCtrl as ctrl">
    {{ ctrl.hero.name }}
    <app></app>
</div>

使用Javascript:

'use strict';

var app = angular.module('app', [
    'ngComponentRouter',
    'testComponent',
])

.config(function($locationProvider) {
    $locationProvider.html5Mode(true);
})

.value('$routerRootComponent', 'app')

.controller('MainCtrl', function(){
    this.hero = {
        name: 'Spawn'
    };
})

.component('app', {
    template: '<ng-outlet></ng-outlet>',
    $routeConfig: [
        {path: '/test', name: 'Test', component: 'testComponent'},
    ],
})

var testComponent = angular.module('testComponent', []);

testComponent.component('testComponent', {
    template: '<span>Name: {{$ctrl.hero.name}}</span>',
    controller: TestComponentController,
    bindings: {
        hero: '=',
    }
});

function TestComponentController() {
}

但是<span>Name: {{$ctrl.hero.name}}</span>并没有显示&#34; Spawn&#34;或任何东西。

3 个答案:

答案 0 :(得分:2)

您无法使用&#34;绑定&#34;路由器组件中的定义,因为组件没有您要控制的任何HTML使用。

如果您需要将数据传递到路由组件,您将访问$ routerOnActivate回调中的路由参数。

https://docs.angularjs.org/guide/component-router

要开始的示例代码:https://github.com/brandonroberts/angularjs-component-router/

答案 1 :(得分:1)

我认为在角度1.x的ngComponentRouter中还没有一个很好的解决方案。由于它仍在积极开发中,我希望在下一次迭代中会出现更好的解决方案。

与此同时,我所做的是我通过require使组件依赖于其父组件。

编辑:我现在明白你想把MainCtrl作为顶级控制器,所以我编辑了代码:

.component('app', {
    template: '<ng-outlet></ng-outlet>',
    bindings: {
      hero: '<' // we have to bind here since you want to pass it from MainCtrl
    },
    $routeConfig: [
        {path: '/test', name: 'Test', component: 'testComponent'}
    ],
})

var testComponent = angular.module('testComponent', []);

testComponent.component('testComponent', {
    template: '<span>Name: {{$ctrl.hero.name}}</span>',
    controller: TestComponentController,
    require: {
        appCtrl: '^app',
    }
});
function TestComponentController() {
  var ctrl = this;
  ctrl.$onInit = function(){
    ctrl.hero = ctrl.appCtrl.hero
  }
}

然后html应该是:

<div ng-app="app" ng-controller="MainCtrl as ctrl">
  <app hero="ctrl.hero"></app>
</div>

查看工作代码:http://codepen.io/bchazalet/pen/qZYzXM?editors=1111

这不是理想的,因为它引入了一个依赖(在你的情况下从testComponent到app),但它可以工作。

答案 2 :(得分:-1)

如果你仍然需要这个,我这个绑定适用于html attr所以你应该是html  enter <div ng-app="app" ng-controller="MainCtrl as ctrl"> {{ ctrl.hero.name }} <app hero="ctrl.hero.name"></app> </div> 你认为应该是你的约束力 bindings: { hero: '<' }

相关问题