Angularjs ng change directive
The ng-change
directive in AngularJS is used to bind a function to the change
event of an HTML element. This event is fired when the value of the element has been changed by the user.
Here is an example of using ng-change
with an input element:
<input type="text" ng-model="text" ng-change="onTextChange()">
In this example, the ng-model
directive is used to bind the value of the input element to a scope variable called text
. The ng-change
directive is used to call the onTextChange
function whenever the value of the input element has been changed by the user.
Here is an example of using ng-change
with a select element:
<select ng-model="selectedItem" ng-options="item.name for item in items" ng-change="onItemSelected()"> <option value="">-- Select an item --</option> </select>
In this example, the ng-model
directive is used to bind the value of the select element to a scope variable called selectedItem
. The ng-options
directive is used to dynamically generate the list of options based on an array of items. The ng-change
directive is used to call the onItemSelected
function whenever a new item is selected by the user.
You can also use the $event
object to access information about the change
event, such as the target element or the new value of the element. Here is an example:
<input type="range" min="0" max="100" ng-model="value" ng-change="onValueChange($event)"> <p>Value: {{ value }}</p>
$scope.onValueChange = function(event) { var target = event.target; var newValue = target.value; console.log('Value changed to:', newValue); };
In this example, the onValueChange
function takes the $event
object as an argument, which can be used to access the target element of the event, as well as the new value of the element. The function logs the new value to the console whenever the value of the input element has been changed by the user.