Angularjs 角度1.5从父组件清除子组件
带用户输入表单的Angular 1.5应用程序。我们有一个称为组合框的自定义共享组件。它本质上是一个下拉选择器,但有css类和许多用于显示不同内容的提示(typeahead、multiselect等),所有这些都基于父级设置的属性(输入) 一旦在组合框组件中选择了一个值,它将在选择时向父级触发一个事件。父元素将存储有关选定元素的信息。组合框子项还设置了显示当前选定项的显示 这一切都很棒。从父级到子级的单向数据流,以及发布回父级的单个事件。但是,现在我希望家长能够清除子组合框。用户可以点击“重置表单”按钮。我不知道最好的方法是什么Angularjs 角度1.5从父组件清除子组件,angularjs,angularjs-components,Angularjs,Angularjs Components,带用户输入表单的Angular 1.5应用程序。我们有一个称为组合框的自定义共享组件。它本质上是一个下拉选择器,但有css类和许多用于显示不同内容的提示(typeahead、multiselect等),所有这些都基于父级设置的属性(输入) 一旦在组合框组件中选择了一个值,它将在选择时向父级触发一个事件。父元素将存储有关选定元素的信息。组合框子项还设置了显示当前选定项的显示 这一切都很棒。从父级到子级的单向数据流,以及发布回父级的单个事件。但是,现在我希望家长能够清除子组合框。用户可以点击“重置表
- 如果我可以重新绘制子组件并使其再次为$onInit,这将起作用
- 我可以将boxValue存储在父级中,但这需要我采用组合框中使用的许多共享逻辑,并在许多表单/页面上复制它
Combo-box.component.js
var ComboBoxComponent = {
restrict: 'E',
transclude: true,
bindings: {
options: '<',
label: '@',
title: '@',
groupBy: '@',
multiselect: '<?',
showCheckAll: '<?',
showUncheckAll: '<?',
disabled: '<?',
required: '<?',
onSelect: '&'
},
templateUrl: '/components/common/combo-box/combo-box.component.html',
controller: function($document, $element, $scope, $filter) {
...
$ctrl.select = function(option) {
if ($ctrl.multiselect) {
$ctrl.selected.push(option);
$ctrl.onSelect({ selectedOptions: $ctrl.selected });
} else {
$ctrl.selected = option;
$ctrl.closeDropDown();
$ctrl.onSelect({ selectedOption: $ctrl.selected });
}
setBoxValue();
};
function setBoxValue() {
if ($ctrl.multiselect) {
if ($ctrl.selected.length > 1) {
$ctrl.boxValue = $ctrl.selected.length + ' items selected';
} else {
if ($ctrl.selected && $ctrl.selected.length > 0) {
$ctrl.boxValue = $ctrl.selected[0][$ctrl.label];
} else {
$ctrl.boxValue = '';
}
}
} else {
$ctrl.boxValue = $ctrl.selected ? $ctrl.selected[$ctrl.label] : '';
}
}
}
var ComboBoxComponent={
限制:'E',
是的,
绑定:{
选项:基本上,您可以向子组件分派事件,也可以公开一些“API”从子组件到父组件,并在需要时使用它。这两种情况都在问题的答案中进行了描述。问题是关于指令,但在本例中几乎相同。我不知道该解决方案如何应用。所选答案使用$scope.$broadcast,我们显然不希望将其用于组件。其他两个answers使用$scope继承,这在使用.component时是不存在的,因为我们总是在隔离的作用域中操作。
var ComboBoxComponent = {
restrict: 'E',
transclude: true,
bindings: {
options: '<',
label: '@',
title: '@',
groupBy: '@',
multiselect: '<?',
showCheckAll: '<?',
showUncheckAll: '<?',
disabled: '<?',
required: '<?',
onSelect: '&'
},
templateUrl: '/components/common/combo-box/combo-box.component.html',
controller: function($document, $element, $scope, $filter) {
...
$ctrl.select = function(option) {
if ($ctrl.multiselect) {
$ctrl.selected.push(option);
$ctrl.onSelect({ selectedOptions: $ctrl.selected });
} else {
$ctrl.selected = option;
$ctrl.closeDropDown();
$ctrl.onSelect({ selectedOption: $ctrl.selected });
}
setBoxValue();
};
function setBoxValue() {
if ($ctrl.multiselect) {
if ($ctrl.selected.length > 1) {
$ctrl.boxValue = $ctrl.selected.length + ' items selected';
} else {
if ($ctrl.selected && $ctrl.selected.length > 0) {
$ctrl.boxValue = $ctrl.selected[0][$ctrl.label];
} else {
$ctrl.boxValue = '';
}
}
} else {
$ctrl.boxValue = $ctrl.selected ? $ctrl.selected[$ctrl.label] : '';
}
}
}