2017-07-02 75 views
2

当使用常规的输入,如

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

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

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

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>' 
    }; 
}); 

样品的用法是

<form name="myForm"> 
    <my-directive foo-bar="myObj.foobarValue"></my-directive> 
</form> 

,并在任何两个按钮的用户点击后,myForm$dirty设置为true。

这是如何完成的?

+0

如果该指令定义每个按钮采取行动,而不是在模板中的任何按钮时,它会更容易些,那可以接受吗? – user2718281

+0

使用[ngFormController API - $ setDirty](https://docs.angularjs.org/api/ng/type/form.FormController#$setDirty) – georgeawg

回答

2

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

使用ngModel controller并在DDO的require property的对象形式:

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 controller,该指令将根据需要自动设置窗体控件。

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>


更新

这看起来很有希望。它甚至看起来像scope: { ngModel: '<' },是不是需要?

在这个例子中,不使用的ng-model输入,但对于较复杂的形式控制元件,我建议隔离与ngModel范围作为输入。输出应该用$setViewValue method完成。

欲了解更多信息,请参阅

+0

我正在构建一个指令,并希望避免代码重复。 – clearpath

+0

查看答案的更新。 – georgeawg

+0

这看起来很有前途。它甚至看起来像''范围:{ngModel:'<'},''不需要? – clearpath