Search code examples
javascriptangularjsngcomponentrouter

Binding in Component Router - Angular 1.5


I'm struggling with binding in Component Router.

It is said in the Developer's Guide you should avoid using $scope in components therefore objects have to be passed through binding.

Based on examples in: https://docs.angularjs.org/guide/component and https://docs.angularjs.org/guide/component-router I came up with:

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() {
}

But <span>Name: {{$ctrl.hero.name}}</span> doesn't show "Spawn" or anything.


Solution

  • You cannot use the "bindings" definition in router components as the component doesn't have any HTML use that you would control.

    If you need to pass in data to the routing component you would access routing parameters in the $routerOnActivate callback.

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

    Sample code to get started here: https://github.com/brandonroberts/angularjs-component-router/