AngularJS custom form component / directive using ng-model

前端 未结 1 945
猫巷女王i
猫巷女王i 2020-11-30 15:33

Angular custom form component / directive and $dirty property

When using regular input, such as

相关标签:
1条回答
  • 2020-11-30 16:05

    Implementing custom form controls (using ngModel)

    Use the ngModel controller and the object form of the require property in the DDO:

    angular.module('myModule', [])
    .directive('myDirective', function() {
      return {
        restrict: 'E',
        require: { ngModelCtrl: 'ngModel' },
        scope: {
          ngModel: '<'
        },
        bindToController: true,
        controllerAs: '$ctrl',
        template: 
           `<div>
              <button ng-click="$ctrl.ngModelCtrl.$setViewValue('foo')">
                  Set foo
              </button>
              <button ng-click="$ctrl.ngModelCtrl.$setViewValue('bar')">
                  Set bar
              </button>
           </div>`,
        controller: function ctrl() {}
      };
    });
    

    Usage:

    <form name="myForm">
        <input type="text" ng-model="foobar">
        <my-directive ng-model="foobar"></my-directive>
    </form>
    

    By instantiating and using the ng-model controller, the directive will automatically set the form controls as necessary.

    The DEMO

    angular.module('myModule', [])
    .directive('myDirective', function() {
      return {
        restrict: 'E',
        require: { ngModelCtrl: 'ngModel' },
        scope: {
          ngModel: '<'
        },
        bindToController: true,
        controllerAs: '$ctrl',
        template: 
           `<div>
              <button ng-click="$ctrl.ngModelCtrl.$setViewValue('foo')">
                  Set foo
              </button>
              <button ng-click="$ctrl.ngModelCtrl.$setViewValue('bar')">
                  Set bar
              </button>
           </div>`,
        controller: function ctrl() {}
      };
    });
    <script src="//unpkg.com/angular/angular.js"></script>
      <body ng-app="myModule">
        <h2>ngModel DEMO</h2>
        <form name="myForm">
            <input type="text" ng-model="foobar">
            <my-directive ng-model="foobar"></my-directive>
        </form>
        <br>myForm.$dirty = {{myForm.$dirty}}
        <br>myForm.$pristine = {{myForm.$pristine}}
        <br><button ng-click="myForm.$setDirty()">Set dirty</button>
        <br><button ng-click="myForm.$setPristine()">Set pristine</button>
      </body>

    I recommend isolate scope with ngModel as an input. Output should be done with the $setViewValue method.

    For more information, see

    • AngularJS Developer Guide - Implementing custom form controls (using ngModel)

    • AngularJS Developer Guide - Component-based application architecture

    0 讨论(0)
提交回复
热议问题