使用 ngRoute resolve 将变量传递给组件

Use ngRoute resolve to pass variable to component

阅读了一些关于 angularJS 1.5 组件的好东西后,我正尝试开始使用它。 我做了一个简单的测试,试图让 "Hello world!" 组件与 "world" 绑定。 我想使用 ngRoute 将该数据传递给组件,但我没能做到。我搜索了但没有找到解决方案。

代码如下:

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: "@"
    }
});

我尝试使用“<”和“=”等不同的绑定,但没有成功。 另请注意,如果我像这样在模板中传递变量,它会起作用:

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

这是一个重现我遇到的问题的 plunker:https://plnkr.co/edit/Aq9wbUi6rZe4hFoFOa31?p=preview

非常感谢您的帮助 ;)

干杯, 耶雷本茨

如果你读过the documentation,你应该明白

  • 解析对象的值应该是函数
  • 已解析的值未直接绑定到组件。它们在模板范围的 $resolve 变量中可用。

所以代码应该是

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: "@"
    }
});

有关演示,请参阅 https://plnkr.co/edit/rMx2SymR6GXT51Souxgt?p=preview