Tôi cần một cái gì đó như thế này trước đây vì vậy tôi nghĩ rằng tôi sẽ chia sẻ cách tôi giải quyết vấn đề này.
Tương tự như OP, tôi cần phải một cách tự do các phương thức kích hoạt trong thành phần con từ thành phần chính. Tôi muốn có thể kích hoạt phương thức này trong phụ huynh một cách tự do/riêng biệt mà không cần sử dụng móc vòng đời $ onChanges. Thay vào đó, tôi đã tạo cơ chế đăng ký thông báo để cho phép thành phần con 'đăng ký' phương thức với cha mẹ khi được tải. Phương thức này sau đó có thể được tự do kích hoạt bởi cha mẹ bên ngoài chu kỳ $ onChanges.
Tôi đã tạo một codepen để minh họa điều này. Nó có thể dễ dàng mở rộng để xử lý các loại thông báo khác nhau từ cha mẹ không liên quan đến các thay đổi dữ liệu.
index.html
<div ng-app="tester">
<parent></parent>
</div>
Script.js
angular.module('tester', []);
angular.module('tester').component('parent', {
controller: parentController,
template: `
<div class="tester-style">
<button ng-click="$ctrl.notifyChild()">Notify child</button>
<child parent-to-child-notification-registration="$ctrl.childComponentNotificationRegistration(handler)">
</div>
`
});
function parentController() {
let childComponentEventHandler = null;
this.$onInit = function() {
this.value = 0;
};
this.childComponentNotificationRegistration = function(handler) {
childComponentEventHandler = handler;
console.log('Child component registered.');
};
this.notifyChild = function() {
if (childComponentEventHandler) {
childComponentEventHandler(this.value++);
}
};
}
angular.module('tester').component('child', {
bindings: {
parentToChildNotificationRegistration: '&',
},
controller: childController,
template: `
<div class="tester-style">
<h4>Child Component</h4>
</div>
`
});
function childController() {
this.$onInit = function() {
this.parentToChildNotificationRegistration({
handler: this.processParentNotification
});
};
this.processParentNotification= function(parentValue) {
console.log('Parent triggered child notification handler!!!');
console.log('Value passed to handler:', parentValue);
};
};
}
Cũng cho một cái gì đó tương tự như @adam0101 's # 3 câu trả lời thấy codepen.
Vui lòng thêm định nghĩa thành phần. – alphapilgrim
Components = https://docs.angularjs.org/guide/component – TkNeo
Không, tôi có nghĩa là mã của bạn, cho thành phần của bạn. Không phải định nghĩa về thành phần là gì. Phần JS thực tế. – alphapilgrim