angularjs 1.5.x 中的子组件通信
child components communications in angularjs 1.5.x
我有一个包含 2 个子组件的 angularjs 组件。当 new-product
组件中的 on-added
输出触发时,我想在 product-list
组件中调用一个函数。
<h1>{{vm.store.title}}</h1>
<product-list store-id="vm.storeId"></product-list>
<new-product store-id="vm.store.id" on-added="$ctrl.productAdded()"></new-product>
productAdded 方法在 product-list
组件中并重新启动产品列表。
任何帮助将不胜感激。
在这种情况下,我认为使用通用父组件并使 product-list
成为接收列表并仅显示它的哑组件会更好。这样父级负责管理这个列表,product-list
负责渲染列表。这允许您处理来自父组件的状态,因为 new-product
也是愚蠢的,它会将更改发送到父组件并将新列表状态传播到子组件(a.k.a。product-list
).
例如,考虑使用类似于这个原始组件树的东西:
<product-manager store-id="$ctrl.storeId">
<h1>{{vm.store.title}}</h1>
<product-list products="vm.store.products"></product-list>
<new-product on-added="vm.productAdded(product)"></new-product>
</product-manager>
或者也许:
<products-page store="$ctrl.store">
<h1>{{ $ctrl.store.title }}</h1>
<product-list products="$ctrl.store.products"></product-list>
<product-form on-save="$ctrl.productAdded(product)"></product-form>
</products-page>
The previous examples are raw representation of a component tree and its templates, in a real situation you'd have <products-page store="$ctrl.store"></products-page>
because it's internal nodes would be defined by its template on the component definition.
我有一个包含 2 个子组件的 angularjs 组件。当 new-product
组件中的 on-added
输出触发时,我想在 product-list
组件中调用一个函数。
<h1>{{vm.store.title}}</h1>
<product-list store-id="vm.storeId"></product-list>
<new-product store-id="vm.store.id" on-added="$ctrl.productAdded()"></new-product>
productAdded 方法在 product-list
组件中并重新启动产品列表。
任何帮助将不胜感激。
在这种情况下,我认为使用通用父组件并使 product-list
成为接收列表并仅显示它的哑组件会更好。这样父级负责管理这个列表,product-list
负责渲染列表。这允许您处理来自父组件的状态,因为 new-product
也是愚蠢的,它会将更改发送到父组件并将新列表状态传播到子组件(a.k.a。product-list
).
例如,考虑使用类似于这个原始组件树的东西:
<product-manager store-id="$ctrl.storeId">
<h1>{{vm.store.title}}</h1>
<product-list products="vm.store.products"></product-list>
<new-product on-added="vm.productAdded(product)"></new-product>
</product-manager>
或者也许:
<products-page store="$ctrl.store">
<h1>{{ $ctrl.store.title }}</h1>
<product-list products="$ctrl.store.products"></product-list>
<product-form on-save="$ctrl.productAdded(product)"></product-form>
</products-page>
The previous examples are raw representation of a component tree and its templates, in a real situation you'd have
<products-page store="$ctrl.store"></products-page>
because it's internal nodes would be defined by its template on the component definition.