javascript - Angular: how to bind to required/ngRequired -
i have directive can required or not. can used in 2 ways (as far know)
<my-foo required></my-foo>
or
<my-foo ng-required="data.value > 10"></my-foo>
so, because require
, ngrequire
same thing think directive this
html:
<my-foo ng-require="data.isrequired"></my-foo>
js:
... .directive('myfoo', function () { return { restrict: 'e', scope: { required: '=' } ...
well, nope, doesn't work, scope.require
undefined
. have change scope definition
scope: { required: '=ngrequired' }
so question preferred way handle both situation such value gets stored in scope.required
? should defined both or use attrs link function ?
there 2 approaches can pick:
1. custom form element supporting ng-model
if peek @ ng-required
directive source code you'll find deals ng-model
controller:
restrict: 'a', require: '?ngmodel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; attr.required = true; // force truthy in case on non input element ctrl.$validators.required = function(modelvalue, viewvalue) { return !attr.required || !ctrl.$isempty(viewvalue); }; attr.$observe('required', function() { ctrl.$validate(); }); }
thus if custom directive supports ng-model
have support ng-required
i.e.:
angular.module('test', []) .directive('myinput', function(){ return { restrict: 'e', require: 'ngmodel', scope: true, template: '<div><button ng-click="changevalue()">change value from: {{currentvalue}}</button></div>', link: function (scope, element, attrs, ngmodelctrl) { ngmodelctrl.$parsers.push(function(val){ if(!val){ return null; } return parsefloat(val, 10) * 100; }); ngmodelctrl.$render = function() { scope.currentvalue = ngmodelctrl.$viewvalue || 'no value'; }; scope.changevalue = function read(){ var newvalue = math.random(); if(newvalue > 0.5){ ngmodelctrl.$setviewvalue(newvalue + ""); } else { ngmodelctrl.$setviewvalue(null); } ngmodelctrl.$render(); }; } }; });
2. wrap existing directive , pass ng-required
:
angular.module('test', []) .directive('myformelement', function() { return { restrict: 'e', scope: { model: '=', required: '=' }, template: '<div>enter number: <input type="number" ng-model="data.number" ng-required="required"></div>' }; });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="test" ng-init="data={value:'initial', required: false}"> <form> required: <input type="checkbox" ng-model="data.required"> <my-form-element required="data.required" model="data"></my-form-element> </form> </div>
Comments
Post a Comment