How to use ng-model directive in AngularJS



Image not found!!

In AngularJS, the ng-model directive is used to bind the value of HTML controls (like input, select, textarea) to application data. It creates a two-way data binding between the model and the view, meaning changes in the model update the view and changes in the view update the model. Here's how you can use it:

  1. Basic Usage:

    You can use ng-model by adding it as an attribute to any HTML control that can hold a value (like input, select, textarea).

    html
    <input type="text" ng-model="name">

    In this example, name is a property in your AngularJS controller's scope. Any changes made to the input field will automatically update the name property in the controller's scope, and vice versa.

  2. Using with Controllers:

    html
    <div ng-controller="MyController"> <input type="text" ng-model="data"> </div>
    javascript
    angular.module('myApp', []) .controller('MyController', function($scope) { $scope.data = 'Initial value'; });
  3. Using with Select:

    html
    <select ng-model="selectedItem" ng-options="item for item in items"> </select>

    In this case, selectedItem will contain the value of the selected option, and items is an array defined in your controller.

  4. Using with Checkbox:

    html
    <input type="checkbox" ng-model="checked">

    checked will be true if the checkbox is checked and false if it's unchecked.

  5. Using with Radio Buttons:

    html
    <input type="radio" ng-model="selected" value="option1"> Option 1
    <input type="radio" ng-model="selected" value="option2"> Option 2

    In this example, selected will contain the value of the selected radio button.

Remember, ng-model creates a two-way binding, so any changes made in the UI (view) will be reflected in the model, and any changes in the model will be reflected in the UI.