2017-07-02 19 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