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()">
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.
Is there an event
, or caller
or something similar that I can use within the context of updateUserData
?
Hopefully something like ng-change="updateUserData(caller)"
The ng-change Directive in AngularJS is used whenever the value of an input element changes. The expression is evaluated immediately whenever there is a change in the input value. It requires an ng-model directive to be present. It is triggered whenever there is any single change in the input.
DOM stands for Document Object Model. AngularJS's directives are used to bind application data to the attributes of HTML DOM elements.
Definition and UsageThe ng-change event is triggered at every change in the value. It will not wait until all changes are made, or when the input field loses focus. The ng-change event is only triggered if there is a actual change in the input value, and not if the change was made from a JavaScript.
"ng" stands for Next Generation, as Angular is the next generation of HTML .
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.
If your HTML is
<select id="hairColorComponent" ng-model="hairColor"
ng-options="option.name for option in hairColorData"
ng-change="updateUserData()">
Then changing the select will change the value of $scope.hairColor
in your controller. In updateUserData()
just read its value and act accordingly.
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.
Found this on google, I eventually solved my problem so here's my solution.
If you just need the ID, you could always just pass that as a parameter.
<select id="hairColorComponent" ng-model="hairColor"
ng-options="option.name for option in hairColorData"
ng-change="updateUserData('hairColorComponent')">
Still not super clean, but it solved my problem. Since I actually needed the dom element, I then used jQuery to get the element.
$scope.updateUserData = function (id) {
var element = jQuery('#'+id);
};
(For those wondering, I'm doing my best with converting legacy code that "magically" saves user settings on pages all over the website.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With