📜  ng model on change - Javascript (1)

📅  最后修改于: 2023-12-03 14:44:35.172000             🧑  作者: Mango

AngularJS: Using ng-model on ng-change

When building forms with AngularJS, it's common to use the ng-model directive to bind input fields to a specific model value. However, what happens when you need to trigger an action in response to changes in that model value? That's where the ng-change directive comes in.

The ng-change directive

The ng-change directive allows you to specify a function to be called whenever the value of an ng-model-bound input changes. For example, let's say you have an input field that asks for the user's name. You might have a ng-model binding like this:

<input type="text" ng-model="user.name">

You could then use ng-change to trigger a function when the user changes their name:

<input type="text" ng-model="user.name" ng-change="updateName()">

In this example, the updateName() function would be called whenever the user changes their name in the input field.

Example: Updating a list of items

Let's say you have a list of items that you want to display on the page, and you also have an input field that allows the user to add new items to the list. Here's one way you could use ng-model and ng-change to accomplish this:

<ul>
  <li ng-repeat="item in items">{{ item }}</li>
</ul>

<input type="text" ng-model="newItem" ng-change="addItem()">

In this example, the items array is bound to a ng-repeat directive, which is used to display all of the items in the array. The newItem variable is used to bind the input field to a new item that the user wants to add to the list. The addItem() function is called whenever the user changes the value of the input field, and it adds the new item to the items array:

$scope.addItem = function() {
  if ($scope.newItem) {
    $scope.items.push($scope.newItem);
    $scope.newItem = '';
  }
};
Conclusion

The ng-change directive is a powerful tool for triggering actions in response to changes in ng-model-bound input fields. By using ng-change to call a function whenever an input field changes, you can create dynamic and responsive forms that deliver a great user experience.