首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用ng-model的AngularJS自定义表单组件/指令?

使用ng-model的AngularJS自定义表单组件/指令?
EN

Stack Overflow用户
提问于 2018-08-01 05:30:17
回答 1查看 0关注 0票数 0

使用常规输入时,如

代码语言:txt
复制
<form name="myForm">
  <input type="text" ng-model="foobar">
</form>

在输入框中输入后myForm.$dirty是真的。

我想创建一个简单的指令,例如

代码语言:txt
复制
angular.module('myModule', [])
.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      fooBar: '='
    },
    template: '<div><button ng-click="fooBar=foo"></button><button ng-click="fooBar=bar"></button></div>'
  };
});

样本使用将是

代码语言:txt
复制
<form name="myForm">
  <my-directive foo-bar="myObj.foobarValue"></my-directive>
</form>

当用户点击这两个按钮中的任何一个后,myForm$dirty都是真的。

这是如何完成的?

EN

回答 1

Stack Overflow用户

发布于 2018-08-01 15:21:59

实现自定义表单控件(使用ngModel

在DDO中使用ngModel控制器和require属性的对象形式:

代码语言:javascript
复制
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() {}
  };
});

用法:

代码语言:javascript
复制
<form name="myForm">
    <input type="text" ng-model="foobar">
    <my-directive ng-model="foobar"></my-directive>
</form>
代码语言:javascript
复制
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() {}
  };
});
代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005886

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档