interpolation - AngularJS: Linking multiple scope variables inside external template -
i trying build custom directives inputs validations provided ngmessages directive. still, can't link multiple variables $scope dynamically determine form name , input name. here's code far:
the directive:
app.directive('textbox', ['$compile', function ($compile) { return { restrict: 'e', scope: { label: "@", fieldname: "@", bindto: "=" }, require: "^form", templateurl: '/webclient/directives/textbox/textboxtemplate.html', link: function (scope, element, attrs, ctrl) { $scope.formname = ctrl.$name; } }; }]);
the template:
<div> <label>{{label}}</label> <input type="text" name="{{fieldname}}" ng-model="{{field}}" required /> <div ng-messages="{{formname}}.{{fieldname}}.$error"> <div ng-message="required">you left field blank...</div> <div ng-message="minlength">your field short</div> <div ng-message="maxlength">your field long</div> <div ng-message="email">your field has invalid email address</div> </div> </div>
the usage:
<text-box bind-to="myfield" field-name="myfield"></text-box>
the issues encounter related ng-messages attribute value. doesn't seem work when use curly braces , renders text "formname.fieldname.$error" if don't. other issue related ng-model, same scenario applies.
thank you!
you can pass formcontroller
, ctrl
in link method directive scope scope.form = ctrl;
.
then can add <div ng-messages="form[fieldname].$error">
access $error
property.
curly braces required name of input field. ng-model can directly add model with-out curlies because ng-model requires two-way binding work.
please have @ demo below or jsfiddle.
angular.module('demoapp', ['ngmessages']) .controller('maincontroller', maincontroller) .directive('textbox', ['$compile', function ($compile) { return { restrict: 'e', scope: { label: "@", fieldname: "@", bindto: "=" }, require: "^form", templateurl: '/webclient/directives/textbox/textboxtemplate.html', link: function (scope, element, attrs, ctrl) { //$scope.formname = ctrl.$name; scope.form = ctrl; } }; }]); function maincontroller($scope) { $scope.myfield = 'test'; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular-messages.js"></script> <div ng-app="demoapp" ng-controller="maincontroller"> <form name="testform"> <text-box bind-to="model" field-name="myfield"></text-box> </form> {{model}} <script type="text/ng-template" id="/webclient/directives/textbox/textboxtemplate.html"> <div> <label>{{label}}</label> <input type="text" name="{{fieldname}}" ng-model="bindto" required /> <div ng-messages="form[fieldname].$error"> <div ng-message="required">you left field blank...</div> <div ng-message="minlength">your field short</div> <div ng-message="maxlength">your field long</div> <div ng-message="email">your field has invalid email address</div> </div> </div> </script> </div>
Comments
Post a Comment