栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

在DDO中使用ngModel控制器和

require
属性的对象形式:

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() {}  };});

用法:

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

通过实例化和使用ng-
model控制器
,该指令将根据需要自动设置表单控件。

演示

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>

我建议隔离范围

ngModel
作为输入。输出应使用$
setViewValue方法完成

有关更多信息,请参见

  • AngularJS开发人员指南-实现自定义表单控件(使用

    ngModel

  • AngularJS开发人员指南-基于组件的应用程序体系结构



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/633233.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号