我正在尝试使用 AngularJS 将事件从子组件传播到父组件。
我有一个父组件,如图所示:
parent.component.js
import angular from 'angular';
import childComponent from './child/child.component'
let parent = {
template: require('./parent.view.html'),
controller: 'parentController',
controllerAs: 'parentCtrl',
};
class parentController {
constructor() {
this.myvalue = 'default';
}
$doCheck(event) {
console.log('new myvalue:' + this.myvalue);
}
}
const parentComponent = 'parent';
angular.module(parentComponent, [childComponent])
.component('parent', parent)
.controller('parentController', parentController);
export default parentComponent;
parent.view.html
<child changevalue="parentCtrl.myvalue = $event.myvalue"></child>
<p>myvalue: {{parentCtrl.myvalue}}</p>
child.component.js
import angular from 'angular';
let child = {
template: require('./child.view.html'),
controller: 'childController',
controllerAs: 'childCtrl',
bindings:{
changevalue: '&'
}
};
class childController {
constructor() {
}
triggerEvent() {
this.changevalue({$event: {myvalue: 'child1'}});
}
}
const childComponent = 'childComponent';
angular.module(childComponent, [])
.component('child', child)
.controller('childController', childController);
export default childComponent;
child.view.html
<button ng-click="childCtrl.triggerEvent()">Select</button>
在 subview 中单击按钮后,我可以成功更改父 View 中的 myvalue
,如父 View 中所示。
但是,此更改不会触发 parent.component.js
中的$onChange()
方法。
此外,此更改会触发 $doChange()
两次。
我希望按钮单击仅触发一次方法调用。
我做错了什么?热切欢迎任何指导。谢谢
最佳答案
- 子组件或多或少没问题。一件事是你不能使用
$
- 这是为 Angular 内部变量和方法保留的。 这是您自制的事件,所以应该没有钱。 - 您不需要组件的 controllerAs 语法 - 默认情况下它是 $ctrl 并且没有必要更改它。
- 在 html 中,最好避免像
ng-click="a = 2"
这样的表达式,从一开始就使用方法。 - 当您直接调用方法时 - 您不需要 $onCheck、$onChanges 或其他任何东西。 $onChanges 和 $onCheck 用于监视绑定(bind)更改 - 如果您更改父项中的某些内容并观察子项中的这些更改,您将需要它们。
最后你有:
let child = {
template: require('./child.view.html'),
controller: 'childController',
bindings:{
changevalue: '&'
}
};
class childController {
constructor() {
}
triggerEvent() {
this.changevalue({event: {myvalue: 'child1'}});
}
}
<button ng-click="$ctrl.triggerEvent()">Select</button>
let parent = {
template: require('./parent.view.html'),
controller: 'parentController',
};
class parentController {
constructor() {
this.myvalue = 'default';
}
setEvent(event) {
this.myvalue = event.myvalue;
console.log('new myvalue:' + this.myvalue);
}
}
<child changevalue="$ctrl.setEvent(event)></child>
<p>myvalue: {{parentCtrl.myvalue}}</p>
关于javascript - AngularJS 1.6 + ES6 - $doCheck 被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47829476/