【问题标题】:How to Properly use the ng-model Directive and its Controller in Custom Directives?如何在自定义指令中正确使用 ng-model 指令及其控制器?
【发布时间】:2018-01-18 22:04:57
【问题描述】:

我创建了一个包含 jstree 的指令,并在我的自定义指令标签中使用了 ng-model 来传递一些 json 数据。

我的问题是:在这种情况下我必须使用ng-model 吗?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-ng-model angularjs-components


    【解决方案1】:

    我创建了一个包含jstree 的指令,并在我的自定义指令标签中使用了ng-model 来传递一些json 数据。在这种情况下我必须使用ng-model 吗?

    ng-model directive 实例化了ngModelController。这是一个启用form validation 的复杂指令,并且是ng-change directive 的先决条件。避免使用ng-model 作为属性名称,除非它按预期使用。欲了解更多信息,请参阅AngularJS Developer Guide - Implementing custom form controls (using ngModel)

    对于数据输入,只需使用one-way < binding

    <my-tree tree-data="vm.treeData">
    </my-tree>
    
    app.component("myTree", {
         bindings: { treeData: '<' }
         template: `<div>my-tree component</div>`,
         controller: function() {}
    })
    

    One-way &lt; binding 从 v1.5 开始可用。只有拥有数据的组件才能对其进行修改,以便于推断更改了哪些数据以及何时更改。


    如何将ng-model 功能添加到组件1

    实现ng-model时,输入使用one-way &lt; binding,输出使用ngModelController API

    app.component("checkboxComponent", {
        bindings: { ngModel: '<' },
        require: { ngModelCtrl: 'ngModel' },
        template: `
              <input type=checkbox ng-model='$ctrl.ngModel'
                     ng-change="$ctrl.ngModelChange()" />
        `,
        controller: function() {
          this.ngModelChange = () => {
            this.ngModelCtrl.$setViewValue(this.ngModel);
          };
        }
    })
    

    组件对输入使用单向绑定,对输出使用$setViewValue。 使用这种方法,ng-change 可以工作,并且组件可以用作表单元素:

    <form name="form1">
         <checkbox-component name="input1" ng-model="vm.formData.input1"
                             ng-change="vm.inp1Change()">
         </checkbox-component>
    </form>
    

    有关详细信息,请参阅

    The DEMO

    angular.module("app",[])
    
    .component("checkboxComponent", {
        bindings: { ngModel: '<' },
        require: { ngModelCtrl: 'ngModel' },
        template: `
            <fieldset>
              <h3>Checkbox Component</h3>
              <input type=checkbox ng-model='$ctrl.ngModel'
                     ng-change="$ctrl.ngModelChange()" />
                     Checkbox
            </fieldset>
        `,
        controller: function() {
          this.ngModelChange = () => {
            this.ngModelCtrl.$setViewValue(this.ngModel);
          };
        }
    })
    <script src="//unpkg.com/angular/angular.js"></script>
      <body ng-app="app">
        <checkbox-component ng-model="value"
                            ng-change="value2=value"> 
        </checkbox-component>
        <fieldset>
          <p>value = {{value}}</p>
          <p>value2 = {{value2}}</p>
        </fieldset>
      </body>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多