如何获得触发NG-变化的DOM元素? [英] How to get the DOM element that triggered ng-change?

查看:90
本文介绍了如何获得触发NG-变化的DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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 函数内更新,而无需手动指定它为每个 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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆