我试图找到一个更好的解决方案,将ui-routerangular components一起使用。

考虑两个简单的组件:

app.component('componentOne', {
  template: '<h1>My name is {{$ctrl.name}}, I am {{$ctrl.age}} years old.</h1>',
  bindings : {
      name : '@',
      age : '@'
    }
  }
);

app.component('componentTwo', {
  template: '<h1>I am component 2</h1>'
});


现在,我使用template属性指定组件及其参数:

 app.config(function($stateProvider, $urlRouterProvider ){
 $stateProvider
    .state('component1', {
      url: "/component1",
      template: "<component-one name=\"foo\" age=\"40\"></component-one>"
    })
    .state('component2', {
      url: "/component2",
      template: "<component-two></component-two>"
    })
});


尽管这很好,但我的组件具有大约十个绑定,这使得ui-router的配置确实很尴尬。

我尝试使用component属性,但这对我根本不起作用。我发现的唯一其他解决方案是使用require属性指定父级并省略绑定-但这对我来说不合适……是否有更好的方法呢?

这是plnkr

最佳答案

UI-Router 1.0+中存在UI-Router component:路由(当前位于1.0.0-beta.1)

这是更新的插件:https://plnkr.co/edit/VwhnAvE7uNnvCkrrZ72z?p=preview

绑定静态值

要将静态数据绑定到组件,请使用component和可返回静态数据的resolve块。

$stateProvider.state('component1', {
  url: "/component1",
  component: 'componentOne',
  resolve: { name: () => 'foo', age: () => 40 }
})


绑定异步值

要绑定异步值,请使用可返回数据承诺的resolve。请注意,一种解决方案可能取决于另一种解决方案:

$stateProvider.state('component1Async', {
  url: "/component1Async",
  component: "componentOne",
  resolve: {
    data: ($http) => $http.get('asyncFooData.json').then(resp => resp.data),
    name: (data) => data.name,
    age: (data) => data.age
  }
});


绑定很多价值

您提到一个组件上有10个绑定。根据要绑定的数据的结构,可以使用JavaScript构造resolve块(毕竟它只是“ javascript”)

var component2State = {
  name: 'component2',
  url: '/component2',
  component: 'componentTwo',
  resolve: {
    data: ($http) => $http.get('asyncBarData.json').then(resp => resp.data)
  }
}

function addResolve(key) {
  component2State.resolve[key] = ((data) => data[key]);
}

['foo', 'bar', 'baz', 'qux', 'quux'].forEach(addResolve);

$stateProvider.state(component2State);

07-24 18:09
查看更多