我不确定如何以正确的方式完成以下任务:
举个例子,考虑一下我想创建自己的自定义单选按钮列表指令,如下所示:
<my-radio-button-list>
<my-radio-button>
...Some HTML content...
</my-radio-button>
<my-radio-button>
...Some HTML content...
</my-radio-button>
<my-radio-button>
...Some HTML content...
</my-radio-button>
</my-radio-button-list>
请注意 - <my-radio-button>
指令不一定使用任何 <input>
元素。
我想要 <my-radio-button>
将有自己的内部事件监听器来跟踪它何时被单击,我也希望当 <my-radio-button>
单击指令,它将通知父级 <my-radio-button-list>
发生此类事件的指令,因此父指令将相应地更改 DOM - 它将取消选择当前选定的项目,并选择被单击的项目。
实现这样的目标的正确方法是什么?
我能想到的唯一方法是在父指令的 Controller 上创建一个方法,该方法将根据需要操作 DOM(它将获取新选定的项目作为参数),然后与其共享父指令的 Controller 子指令(以便他们可以从单击事件处理程序中调用此方法)。然而,我知道这种方法是错误的,因为 Controller 永远不应该操作 DOM。
谢谢!
最佳答案
使用事件(不仅仅是点击事件)将是一种简单的方法。
子(我的单选按钮)html:
<button ng-click="childController.handleClick()">{{childController.childData.id}}</button>
<span ng-if="parentController.currentSelection.id === childController.childData.id">THERE CAN ONLY BE ONE!!!</span>
子(我的单选按钮) Controller :
controller.childData = {id: 'child1'};
controller.handleClick = function(){
$scope.$emit('childClicked', childData);
};
父级(my-radio-button-list)html:
<div>
<ng-transclude></ng-transclude>
<div>
父(my-radio-button-list) Controller :
$scope.$on('childClicked', function(childData){
controller.currentSelection = childData;
});
关于javascript - 由于子指令引发的事件而操作父指令的 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33488717/