我正在为组件路由器中的绑定而奋斗。
开发人员指南中说,您应该避免在组件中使用$scope,因此必须通过绑定传递对象。
基于“:https://docs.angularjs.org/guide/component”和“https://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>没有显示“产卵”之类的东西。
发布于 2016-04-20 06:35:01
您不能在路由器组件中使用“绑定”定义,因为该组件没有您要控制的任何HTML使用。
如果需要将数据传递给路由组件,则将访问$routerOnActivate回调中的路由参数。
https://docs.angularjs.org/guide/component-router
这里开始使用的示例代码:https://github.com/brandonroberts/angularjs-component-router/
发布于 2016-04-14 11:35:43
我不认为有一个很好的解决方案,但在ngComponentRouter的角度为1.x。由于它仍在积极开发中,我希望在下一次迭代中会出现更好的解决方案。
同时,我所做的是使组件依赖于它的父级需求。
编辑:我现在明白了,您希望保持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),但它可以工作。
发布于 2016-04-11 13:39:36
如果您还需要这个,我这个绑定与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: '<' }。
https://stackoverflow.com/questions/36426789
复制相似问题