Use ngRoute resolve to pass variable to component

Issue

After reading some nice stuff about angularJS 1.5 components, I’am trying to start using it.
I did a simple test trying to have a “Hello world!” component with the “world” being a binding.
I would like to use ngRoute to pass that data to the component, but I didn’t manage to do it. I searched but didn’t find a solution.

Here’s the code:

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

app.config(function($routeProvider) {
    $routeProvider.when('/', {
        template: '<component1></component1>',
        resolve: {
          name: 'world'
        }
    });
});

app.component('component1',{
    template: '<h1>Hello {{$ctrl.name}}!',
    bindings: {
        name: "@"
    }
});

I tried with different bindings like “<” and “=” without success.
Please also note that it is working if I pass the variable in the template like this:

app.config(function($routeProvider) {
    $routeProvider.when('/', {
        template: '<component1 name="world"></component1>'
    });
});

Here’s a plunker that reproduces the issue I have: https://plnkr.co/edit/Aq9wbUi6rZe4hFoFOa31?p=preview

Your help would be highly appreciated 😉

Cheers,
Jerebenz

Solution

If you read the documentation, you should understand that

  • the values of the resolve object are supposed to be functions
  • the resolved values are not directly bound to components. They’re available in the template scope’s $resolve variable.

So the code should be

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

app.config(function($routeProvider) {
    $routeProvider.when('/', {
        template: '<component1 name="{{ $resolve.name }}"></component1>',
        resolve: {
          name: function() { return 'world'; }
        }
    });
});

app.component('component1',{
    template: '<h1>Hello {{$ctrl.name}}!',
    bindings: {
        name: "@"
    }
});

See https://plnkr.co/edit/rMx2SymR6GXT51Souxgt?p=preview for a demo.

Answered By – JB Nizet

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.