如何获得触发NG-变化的DOM元素? [英] How to get the DOM element that triggered ng-change?
问题描述
我使用angularJS。我有几个<选择>我页
元素,每个都有自己的 NG-变化
,例如:
I'm using angularJS. I have a few <select>
elements on my page, each with its own ng-change
, for example:
<select id="hairColorComponent" ng-model="hairColor"
ng-options="option.name for option in hairColorData"
ng-change="updateUserData()">
我希望能够确定哪些DOM元素得到了来自 updateUserData code>函数内更新,而无需手动指定它为每个
NG-变化
属性。
I want to be able to determine which DOM element got updated from within the updateUserData
function, without having to manually specify it as a parameter for each ng-change
attribute.
有一个事件
或主叫
或类似的,我可以<$ C的范围内使用的东西$ C> updateUserData code>?
Is there an event
, or caller
or something similar that I can use within the context of updateUserData
?
希望像 NG-变化=updateUserData(主叫)
推荐答案
有没有(易)的方式设计,以做到这一点。角控制器都应该是完全独立的DOM,所以如果你发现自己需要引用DOM在其中你可能接近事物的错误的方式。
There's no (easy) way to do this by design. Angular controllers are supposed to be completely separate of the DOM, so if you find yourself needing to reference the DOM in them you're probably approaching things the wrong way.
如果您的HTML是
<select id="hairColorComponent" ng-model="hairColor"
ng-options="option.name for option in hairColorData"
ng-change="updateUserData()">
然后更改选择将您的控制器更改 $ scope.hairColor
的价值。在 updateUserData()
只是读它的价值和采取相应的行动。
Then changing the select will change the value of $scope.hairColor
in your controller. In updateUserData()
just read its value and act accordingly.
如果您的情况真的没有办法做到这一点,除了引用DOM,你可以通过编写自定义的指令去做。一般来说,在角直接的DOM操作应该是最后的手段一种措施虽然。
If in your situation there's really no way to do it except referencing the DOM, you could do it by writing a custom directive. In general, direct DOM manipulation in Angular should be a last resort kind of measure though.
这篇关于如何获得触发NG-变化的DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!