2016-04-05 106 views
0

我很努力与组件路由器绑定。绑定在组件路由器 - 角1.5

在开发人员指南中说,您应该避免在组件中使用$ 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>不显示 “再生侠” 或任何东西。

回答

-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: '<' }

+0

它不工作,看Codepen:http://codepen.io/srokatonie/pen/wGjRRm – srokatonie

+0

是的,因为你没有'<应用程序的英雄=“ctrl.hero.name”>'而不是你有'',从我的经验来看,'ng-outlet'只能绑定$$路由器。你需要通过html attr来传递你的绑定的值。我会建议从主要组件分离应用程序组件,所以你有'<主要英雄=' –

1

我不认为这是一个很好的解决方案那在ngComponentRouter for angular 1.x中。由于它仍处于积极的发展阶段,我希望在下一次迭代中会出现更好的解决方案。

在此期间,我所做的是我通过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> 

见工作codepen:http://codepen.io/bchazalet/pen/qZYzXM?editors=1111

这并不理想,因为它引入了依赖项(在你的情况下,从testComponent到应用程序),但它的工作原理。

+0

嗨@Boris,这是不工作既不... ... http://codepen.io/srokatonie/pen/jqxXgX – srokatonie

+0

看到一个工作分叉你的codepen(我会更新我的回应同时):http://codepen.io/bchazalet/pen/qZYzXM?editors=1111 – Boris

+0

@srokatonie现在为你工作? – Boris