Prevent repetition in directive attributes? - angularjs

I have a directive which adds an input inside a bootstrap form-group / form-control
It watches the field's $valid and $invalid values, and sets appropriate bootstrap error/valid css classes.
This is the markup:
<fe-input ng-model='user.first_name' field='first_name' submitted='submitted' label='First Name'></fe-input>
<fe-input ng-model='user.last_name' field='last_name' submitted='submitted' label='Last Name'></fe-input>
<fe-input ng-model='user.phone' field='phone' submitted='submitted' label='Phone'></fe-input>
It relies on a scope variable submitted being set when the user attempts to submit the form (so we don't show invalid fields before the user has done anything)
You can see there is a lot of repetition.
field = model.field : the field name is always the same as the model field name
submitted='submitted' : repeated every time
Ideally I'd like to cut it down to this:
<fe-input ng-model='user.first_name' label='First Name'></fe-input>
<fe-input ng-model='user.last_name' label='Last Name'></fe-input>
<fe-input ng-model='user.phone' label='Phone'></fe-input>
It would enforce:
form field's name is always the same as model's field name
submitted on the parent scope is implicitly required
Questions:
Is this even possible?
If so, any suggestions on how to achieve this?
Plunker:
Here is a plunker showing what I've currently got.
Directive source code:
This is my directive's html template:
<div class="form-group" ng-class="{ 'has-success': submitted && isValid,
'has-error' : submitted && isInvalid }">
<label class="control-label" for="{{ field }}">
{{ label }}
</label>
<input type="text"
class="form-control"
ng-model="model"
name="{{ field }}"
id="{{ field }}"
required>
</div>
and the directive source:
angular.module('directive.form-elements', []).directive('feInput', function() {
return {
restrict: 'E',
require: ['^form'],
scope: {
model: '=ngModel',
label: '#',
field: '#',
submitted: '=' // feedback only when the form has been submitted
},
templateUrl: 'components/form-elements/input.html',
replace: true,
link: function (scope, element, attrs) {
scope.$parent.$watch('form.'+scope.field+'.$valid', function(isValid) {
scope.isValid = isValid;
});
scope.$parent.$watch('form.'+scope.field+'.$invalid', function(isInvalid) {
scope.isInvalid = isInvalid;
});
}
};
});
submitted:
submitted is a variable in the form controller's scope, and is shared by all the input elements in the form. It exists solely to enable the valid/invalid styling only when the user has actually attempted to submit the form
angular.module('myApp').controller('UserCtrl', function($scope) {
$scope.submitted = false;
$scope.submit = function(form) {
$scope.submitted = true;
if (!form.$valid)
return;
// do submit
});

One solution is to create a parent directive that handles the repetitive stuff. The HTML could look something like this:
<form name="userForm" fe-form="user">
<fe-input field='first_name' label='First Name'></fe-input>
<fe-input field='last_name' label='Last Name'></fe-input>
<fe-input field='phone' label='Phone'></fe-input>
<button type="submit">Save</button>
<form>
The parent directive:
angular.module('directive.form-elements', []).directive('feForm', function() {
return {
controller: function($scope, attrs) {
var formName = $attrs.name;
var submitted = false;
this.hasSuccess = function(field) {
return submitted && $scope[formName][field].$valid;
};
this.hasError = function(field) {
return submitted && $scope[formName][field].$invalid;
};
this.setSubmitted = function(value) {
submitted = value;
}
},
link: function (scope, element, attrs, controller) {
controller.model = $scope[$attrs.feForm];
element.on('submit', function(event) {
controller.setSubmitted(true);
The important thing is that it has a controller that can be used by your other directive. We also encapsulate the error and success state.
Your original directive:
angular.module('directive.form-elements', []).directive('feInput', function() {
return {
restrict: 'E',
require: ['^form', '^feForm'],
scope: {
field: '#',
label: '#'
},
templateUrl: 'components/form-elements/input.html',
replace: true,
link: function (scope, element, attrs, controllers) {
var feFormController = controllers[1];
scope.model = feFormController.model;
scope.hasSuccess = feFormController.hasSuccess;
scope.hasError = feFormController.hasError;
}
};
});
Here we can use the controller of the parent directive.
Small modifications of your template:
<div class="form-group" ng-class="{ 'has-success': hasSuccess(field),
'has-error' : hasError(field) }">
<label class="control-label" for="{{ field }}">
{{ label }}
</label>
<input type="text"
class="form-control"
ng-model="model[field]"
name="{{ field }}"
id="{{ field }}"
required>
</div>
Please understand that while this code may work for you, it's rather meant as illustration, or a starting point if you will.

Related

Deselectable radio not tracking previous value correctly

I'm trying to create a simple directive that I can apply to an existing radio input to make it deselectable...it doesn't quite work as the directive is not tracking the previously clicked value correctly. The goal is to have the radio set to 'true', 'false', or null if the currently selected value is the same as the previous (clicking true twice for example will unset the radio and set the model value to null). It seems to continually lose track of the previous value which gets set to undefined. I think I'm maybe making some kind of scoping issue but I'm not sure.
Here is the directive:
angular.module('App').directive('deselectableRadio', function() {
return {
restrict: 'A',
scope: {
model: '=ngModel'
},
link: function(scope, element, attr) {
var previousValue = angular.copy(scope.model);
element.bind('click', function(e) {
determineState(element[0]);
});
function determineState(elem) {
if (elem.checked && elem.value == previousValue) {
elem.checked = false;
scope.model = null;
}
previousValue = angular.copy(scope.model);
}
}
}
});
And here is the HTML:
<div class="app-radio">
<input type="radio" name="toggle" id="toggle-yes" value="true"
ng-model="props['toggle']" deselectable-radio>
<label for="toggle-yes">Yes</label>
</div>
<div class="app-radio">
<input type="radio" name="toggle" id="toggle-no" value="false"
ng-model="props['toggle']" deselectable-radio>
<label for="toggle-no">No</label>
</div>
The directive is fighting the ng-model controller.
Instead of creating an isolate scope and a two-way binding to the ng-model attribute, use the ngModelController API.
The DEMO
angular.module('app',[])
.directive('deselectableRadio', function() {
return {
restrict: 'A',
scope: false,
//scope: {
// model: '=ngModel'
//},
require: "ngModel",
link: function(scope, element, attrs, ctrl) {
element.on('click', function(e) {
if (attrs.value == ctrl.$viewValue) {
ctrl.$setViewValue(null);
ctrl.$render();
}
});
}
};
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<div class="app-radio">
<input type="radio" name="toggle" id="toggle-yes" value="true"
ng-model="props['toggle']" deselectable-radio>
<label for="toggle-yes">Yes</label>
</div>
<div class="app-radio">
<input type="radio" name="toggle" id="toggle-no" value="false"
ng-model="props['toggle']" deselectable-radio>
<label for="toggle-no">No</label>
</div>
<br>
model = {{props.toggle || 'null'}}
</body>

Validating custom directive inside a form

I've a form which contains a custom directive that I want to validate. I could do that if the scope is not an isolate scope, but how to proceed if we have an isolate scope case? Here is an example where the form contains 2 fields: first and last name. First name is directly on the form but the last name is within a directive. When i hit 'Save' only first name gets validated. Can somebody point out what am I missing? Code goes somewhat like this:
Main form:
<form class=" form form-group" name="personForm" ng-submit="saveInfo(personForm.$valid, '#/success')" novalidate>
<label for="fname"><strong>First Name:</strong></label>
<input type="text"
name="fname"
class="form-control"
ng-model="person.firstname"
ng-maxlength=10
ng-minlength=3
ng-required="true">
<div class="error-message" ng-messages="personForm.fname.$error" data-ng-if="interacted(personForm.fname)">
<div ng-message="required">This is a required field</div>
<div ng-message="maxlength">max length should be 10</div>
<div ng-message="minlength">min length should be 3</div>
</div>
<last-name ng-model="person"></last-name>
<br/>
<button class="btn btn-primary" type="submit">Save</button>
and the directive (last name):
<label for="lname"><strong>Last Name:</strong></label>
<input type="text"
name="lname"
class="form-control"
ng-model="person.lastname"
ng-maxlength=20
ng-minlength=5
ng-required="required">
<div ng-messages="personForm.lname.$error" data-ng-if="interacted(personForm.lname)">
<div ng-message="required">This is a required field</div>
<div ng-message="maxlength">max length of last name should be 20</div>
<div ng-message="minlength">min length of last name should be 5</div>
</div>
... and finally here is my javascript:
var app = angular.module('MyApp',['ngRoute','ngMessages']);
app.config(function ($routeProvider) {
$routeProvider
.when('/success', {
templateUrl: 'success.html'
})
.when('/', {
templateUrl: 'first-name.html',
controller: 'MyController'
})
})
app.directive('lastName', function() {
return {
restrict: 'E',
scope: {
person: '=ngModel',
},
require:'ngModel',
templateUrl: 'last-name.html'
}
});
app.controller('MyController', function($scope, $location) {
$scope.person = {};
$scope.submitted = false;
$scope.interacted = function(field) {
return $scope.submitted || field.$dirty;
};
$scope.saveInfo = function(isValid, url) {
$scope.submitted = true;
if (isValid) {
$location.path(url);
} else {
alert('Missing values in mandatory fields');
}
}
});
I kinda solved my problem.This is a "poor man's solution" per se so i implore the experts reading this post to suggest me a better way.
My issue was "how will the directive know, if it's parent form has been submitted" (without sharing the scope). My answer was to send another attribute into the directive that indicated the form submission (scope: { formSubmitted: '='}).
app.directive('lastName', function() {
return {
restrict: 'E',
scope: {
formSubmitted: '='
},
require:'ngModel',
templateUrl: './last-name.html',
link: function(scope, element, attrs, controllers) {
scope.$watch('lastname', function() {
controllers.$setViewValue(scope.lastname);
});
}
};
});
So the directive looks a bit silly :( but works.
<last-name ng-model="person.lastname" form-submitted="submitted"></last-name>
... and the "submitted" was something that was used anyways to detect if submit button was pushed.
So with that and some help of other posts on stack overflow (ng-form: to enclose the elements in the directive), I was able to get it working. Here is the plunker for the same.

Get access to form controller validation errors in a custom directive

I have a directive that wraps a form element with some inputs. One of the options is passing in a formName. Usually, with a form with the example name of myForm, to show an error you would do something like myForm.firstName.$error.required.
But, how do I get access to the errors when the form name is dynamically being passed in to the directive?
example usage
<my-custom-form formName='myForm' formSubmit='parentCtrl.foo()'></my-custom-form>
directive
angular.module('example')
.directive('myCustomForm', [
function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'myCustomForm.directive.html',
scope: {
fornName: '#',
formSubmit: '&'
},
require: ['myCustomForm', 'form'],
link: function(scope, element, attrs, ctrls) {
var directiveCtrl = ctrls[0];
var formCtrl = ctrls[1];
scope.data = {};
scope.hasError = function(field) {
// how do i show the errors here?
};
scope.onSubmit = function() {
scope.formSubmit();
};
}
};
}]);
template
<form name="{{ formName }}" ng-submit="onSubmit()" novalidate>
<div class="form-group" ng-class="{'is-invalid': hasError('fullName') }">
<input type="text" name="fullName" ng-model="data.full_name" required />
<div ng-show="hasError('fullName')">
<p>How do I show this error?</p>
</div>
</div>
<div class="form-group" ng-class="{'is-invalid': hasError('email') }">
<input type="text" name="email" ng-model="data.email" ng-minlength="4" required />
<div ng-show="hasError('email')">
<p>How do I show this error?</p>
</div>
</div>
<button type="submit">Submit</button>
</form>
I think the only problem with your code is that the directive requires itself, I don't think that will work. Just removing the myCustomForm from the require works fine.
To check if the field has errors, you just need to check if the $error object in the form controller is empty.
require: ['form'],
link: function(scope, element, attrs, ctrls) {
var formCtrl = ctrls[0];
scope.data = {};
scope.hasError = function(field) {
// Field has errors if $error is not an empty object
return !angular.equals({}, formCtrl[field].$error);
};
Plunker

How to show form input errors using AngularJS UI Bootstrap tooltip?

For example I have the form where I am showing form input errors.
I need to show red badge (with 'hover to show errors') near input label if there are some errors. If user will hover this red badge - he will see list of errors using AngularJS UI Bootstrap tooltip.
I don't want to put list of errors into tooltip-html-unsafe attribute, because it is not convenient to edit and maintain.
This code is more declarative:
<validation-tooltip ng-show="appForm.number.$invalid && appForm.number.$dirty">
<ul>
<li ng-show="appForm.number.$error.required">this field is required</li>
<li ng-show="appForm.number.$error.number">should be number</li>
<li ng-show="appForm.number.$error.min">minimum - 5</li>
<li ng-show="appForm.number.$error.max">miximum - 20</li>
</ul>
</validation-tooltip>
than this code:
<span tooltip-html-unsafe="{{<ul><li>This field is required;</li><li>...</li></ul>}}">hover to show errors</span>
How can I write such validation-tooltip directive using AngularJS UI Bootstrap tooltip?
Or maybe can you suggest another approach to maintain validation error messages?
Demo Fiddle
Validation Tooltip Directive
The validationTooltip is the main directive. It has the following responsibilities:
Define the tool tip template through its transcluded contents
Keep track of validation expressions so that they can be evaluated with each digest cycle.
Expose a controller API for allowing valiationMessage directives to register themselves
Provide a 'target' attribute on the directive to specify which form field the badge (and the associated tooltip) will be bound to
Additional Notes
The tooltip template uses the transclusion function from the link function to bind the template to the directive's scope. There are two properties that are within scope that the template can bind to:
$form: Bound to the form model defined in parent scope. i.e. $scope.myForm
$field: Bound to the form.name model in parent scope. i.e. $scope.myForm.myInput
This allows the template to bind to validation properties such as $valid, $invalid, $pristine, $dirty, and $error without referring to the form name or the input field's name directly. For example, all of the following expressions are valid binding expressions:
$form properties:
`$form.$valid`
`$form.$invalid`
`$form.$dirty`
`$form.$pristine`
`$form.$error.required` etc...
$field properties:
`$field.$valid`
`$field.$invalid`
`$field.$dirty`
`$field.$pristine`
`$field.$error.required` etc...
Directive Implementation
app.directive('validationTooltip', function ($timeout) {
return {
restrict: 'E',
transclude: true,
require: '^form',
scope: {},
template: '<span class="label label-danger span1" ng-show="errorCount > 0">hover to show err</span>',
controller: function ($scope) {
var expressions = [];
$scope.errorCount = 0;
this.$addExpression = function (expr) {
expressions.push(expr);
}
$scope.$watch(function () {
var count = 0;
angular.forEach(expressions, function (expr) {
if ($scope.$eval(expr)) {
++count;
}
});
return count;
}, function (newVal) {
$scope.errorCount = newVal;
});
},
link: function (scope, element, attr, formController, transcludeFn) {
scope.$form = formController;
transcludeFn(scope, function (clone) {
var badge = element.find('.label');
var tooltip = angular.element('<div class="validationMessageTemplate tooltip-danger" />');
tooltip.append(clone);
element.append(tooltip);
$timeout(function () {
scope.$field = formController[attr.target];
badge.tooltip({
placement: 'right',
html: true,
title: clone
});
});
});
}
}
});
Validation Message Directive
The validationMessage directive keeps track of the validation messages to display in the tooltip. It uses ng-if to define the expression to evaluate. If there is no ng-if found on the element, then the expression simply evaluates to true (always shown).
app.directive('validationMessage', function () {
return {
restrict: 'A',
priority: 1000,
require: '^validationTooltip',
link: function (scope, element, attr, ctrl) {
ctrl.$addExpression(attr.ngIf || true );
}
}
});
Usage in HTML
Add a form with a name attribute
Add one or more form fields - each with a name attribute and an ng-model directive.
Declare a <validation-tooltip> element with a target attribute referring to the name of one of the form fields.
Apply the validation-message directive to each message with an optional ng-if binding expression.
<div ng-class="{'form-group': true, 'has-error':form.number.$invalid}">
<div class="row">
<div class="col-md-4">
<label for="number">Number</label>
<validation-tooltip target="number">
<ul class="list-unstyled">
<li validation-message ng-if="$field.$error.required">this field is required </li>
<li validation-message ng-if="$field.$error.number">should be number</li>
<li validation-message ng-if="$field.$error.min">minimum - 5</li>
<li validation-message ng-if="$field.$error.max">miximum - 20</li>
</ul>
</validation-tooltip>
</div>
</div>
<div class="row">
<div class="col-md-4">
<input type="number" min="5" max="20" ng-model="number" name="number" class="form-control" required />
</div>
</div>
</div>
#pixelbits answer is great. I used this instead:
<div class="form-group" ng-class="{ 'has-error': form.name.$dirty && form.name.$invalid }">
<label for="name" class="col-sm-4 control-label">What's your name?</label>
<div class="col-sm-6">
<input class="form-control has-feedback" id="name" name="name"
required
ng-minlength="4"
ng-model="formData.name"
tooltip="{{form.name.$valid ? '' : 'How clients see your name. Min 4 chars.'}}" tooltip-trigger="focus"
tooltip-placement="below">
<span class="glyphicon glyphicon-ok-sign text-success form-control-feedback" aria-hidden="true"
ng-show="form.name.$valid"></span>
</div>
</div>
The technique is ui-bootstrap's tooltip and set the tooltip text to '' when valid.
http://jsbin.com/ditekuvipa/2/edit
Great answer from #pixelbits. I used his directives and modified them slightly to allow the tooltip to display over the actual input as some users requested.
angular.module('app')
.directive('validationTooltip', ['$timeout', function ($timeout) {
function toggleTooltip(scope) {
if (!scope.tooltipInstance) {
return;
}
$timeout(function() {
if (scope.errorCount > 0 && (scope.showWhen == undefined || scope.showWhen())) {
scope.tooltipInstance.enable();
scope.tooltipInstance.show();
} else {
scope.tooltipInstance.disable();
scope.tooltipInstance.hide();
}
});
}
return {
restrict: 'E',
transclude: true,
require: '^form',
scope: {
showWhen: '&',
placement: '#',
},
template: '<div></div>',
controller: ['$scope', function ($scope) {
var expressions = [];
$scope.errorCount = 0;
this.$addExpression = function (expr) {
expressions.push(expr);
}
$scope.$watch(function () {
var count = 0;
angular.forEach(expressions, function (expr) {
if ($scope.$eval(expr)) {
++count;
}
});
return count;
}, function (newVal) {
$scope.errorCount = newVal;
toggleTooltip($scope);
});
}],
link: function (scope, element, attr, formController, transcludeFn) {
scope.$form = formController;
transcludeFn(scope, function (clone) {
var tooltip = angular.element('<div class="validationMessageTemplate" style="display: none;"/>');
tooltip.append(clone);
element.append(tooltip);
$timeout(function () {
scope.$field = formController[attr.target];
var targetElm = $('[name=' + attr.target + ']');
targetElm.tooltip({
placement: scope.placement != null ? scope.placement : 'bottom',
html: true,
title: clone,
});
scope.tooltipInstance = targetElm.data('bs.tooltip');
toggleTooltip(scope);
if (scope.showWhen) {
scope.$watch(scope.showWhen, function () {
toggleTooltip(scope);
});
}
});
});
}
}
}]);
The major change is that the directive uses jQuery to find the target element (which should be an input) via the name attribute, and initializes the tooltip on that element rather than the element of the directive. I also added a showWhen property to the scope as you may not always want your tooltip to show when the input is invalid (see example below).
The validationMessage directive is unchanged
angular.module('app').directive('validationMessage', function () {
return {
restrict: 'A',
priority: 1000,
require: '^validationTooltip',
link: function (scope, element, attr, ctrl) {
ctrl.$addExpression(attr.ngIf || true);
}
}
});
Usage in Html is also similar, with just the addition of showWhen if you want:
<div class="form-group" ng-class="{ 'has-error' : aForm.note.$invalid && (aForm.note.$dirty) }">
<label class="col-md-3 control-label">Note</label>
<div class="col-md-15">
<textarea
name="note"
class="form-control"
data-ng-model="foo.Note"
ng-required="bar.NoteRequired"></textarea>
<validation-tooltip target="note" show-when="aForm.note.$invalid && (aForm.note.$dirty)">
<ul class="validation-list">
<li validation-message ng-if="$field.$error.required">Note required</li>
</ul>
</validation-tooltip>
</div>
</div>
you can actually just use the tooltip-enable property:
<div class="showtooltip" tooltip-placement="left" tooltip-enable="$isValid" tooltip="tooltip message"></div>
My goal was to leverage both ng-messages and ui-bootstrap popover for validation feedback. I prefer the popover vs. the tooltip as it displays the help-block styles more clearly.
Here's the code:
<!-- Routing Number -->
<div class="form-group-sm" ng-class="{ 'has-error' : form.routingNumber.$invalid && !form.routingNumber.$pristine }">
<label class="control-label col-sm-4" for="routing-number">Routing #</label>
<div class="col-sm-8">
<input class="form-control input-sm text-box"
id="routing-number"
name="routingNumber"
ng-model="entity.ROUTINGNUM"
popover-class="help-block"
popover-is-open="form.routingNumber.$invalid"
popover-trigger="none"
required
uib-popover-template="'routing-number-validators'"
string-to-number
type="number" />
</div>
<!-- Validators -->
<script type="text/ng-template" id="routing-number-validators">
<div ng-messages="form.routingNumber.$error">
<div ng-messages-include="/app/modules/_core/views/validationMessages.html"></div>
</div>
</script>
</div>
Here is the validationMessages.html
<span ng-message="required">Required</span>
<span ng-message="max">Too high</span>
<span ng-message="min">Too low</span>
<span ng-message="minlength">Too short</span>
<span ng-message="maxlength">Too long</span>
<span ng-message="email">Invalid email</span>
Note: I had to upgrade to jQuery 2.1.4 to get the uib-popover-template directive to work.
Dependencies:
string-to-number
UI Bootstrap
ng-messages

ng-model is not bind with controller's $scope when I am creating a form dynamically using directive.

view code:- mydir is my custom directive
<div ng-model="vdmodel" mydir="dataValue">
</div>
my directive :-
app.directive('mydir',['$translate',function($translate){
return {
restrict: 'A',
transclude: true,
scope: {dir:'=mydir'},
compile: function(element, attrs) {
return function(scope, element, attrs, controller){
var setTemplate = '';
var setOpt = '';
if(scope.dir.itemtype== 'NUMBER'){
setTemplate = '<input type="number" class="form-control form-font ng-animate ng-dirty"';
setTemplate +='" ng-model="dir[somevalue]" value="'+scope.sizing.somevalue+'" >';
element.html(setTemplate);
}
}
}
}
});
There are many more form element in directive, but when I am trying to submit and collect value in my controller function I get nothing.
What I am doing wrong and what is the best way to collect form values ?
there are quiet a few changes that you will need to do
1.as you are using isolate scope, pass ngModel as well to the directive
scope: {dir:'=mydir', ngModel: '='},
2.as per the best practise ngModel must always have a dot
ng-model="params.vdmodel"
3.make sure to initialize the params object in controller
$scope.params = {}
Usually, a directive would share the same scope as the parent controller but since you are defining a scope in your directive, it sets up it's own isolate scope. Now since the controller and directive have their seperate scope, you need a way to share the data between them which is now done by using data: "=" in scope.
The app code
var myApp = angular.module('myApp', []);
myApp.controller('myController', function ($scope, $http) {
$scope.vdmodel = {};
})
.directive("mydir", function () {
return {
restrict: "A",
scope:{
data:"=model",
dir:'=mydir'
},
templateUrl: 'test/form.html'
};
});
The form.html
<form>
Name : <input type="text" ng-model="data.modelName" /><br><br>
Age : <input type="number" ng-model="data.modelAge" /><br><br>
Place : <input type="text" ng-model="data.modelPlace" /><br><br>
Gender:
<input type="radio" ng-model="data.modelGender" value="male"/>Male<br>
<input type="radio" ng-model="data.modelGender" value="female"/>Female<br><br><br>
</form>
The page.html
<div ng-app="myApp" >
<div ng-controller="myController" >
<div model="vdmodel" mydir="dataValue"></div>
<h3>Display:</h3>
<div>
<div>Name : {{myData.modelName}} </div><br>
<div>Age : {{myData.modelAge}}</div><br>
<div>Place : {{myData.modelPlace}}</div><br>
<div>Gender : {{myData.modelGender}}</div><br>
</div>
</div>
</div>
You have to use $compile service to compile a template and link with the current scope before put it into the element.
.directive('mydir', function($compile) {
return {
restrict: 'A',
transclude: true,
scope: {
dir: '=mydir'
},
link: function(scope, element, attrs, controller) {
var setTemplate = '';
var setOpt = '';
if (scope.dir.itemtype == 'NUMBER') {
setTemplate = '<input type="number" class="form-control form-font ng-animate ng-dirty"';
setTemplate += '" ng-model="dir.somevalue" value="' + scope.dir.somevalue + '" >';
element.html($compile(setTemplate)(scope));
}
}
}
});
See the plunker below for the full working example.
Plunker: http://plnkr.co/edit/7i9bYmd8blPNHch5jze4?p=preview

Resources