I am currently developing a custom directive that will show a set of buttons for incrementing or decrementing the value in an input field when it is in focus. The buttons represent Imperial units such as 1/8", 1/4", and 1/2".
The primary issue I'm facing is that when a button is clicked, the input field loses focus causing the buttons to disappear as per the directive.
Another challenge I'm encountering is figuring out how to access the ngModel to correctly update the input value based on the button pressed. Although I placed the directive around the input for layout purposes, I'm open to suggestions on how to streamline this process by directly tying it to the input element.
Below is my current code setup:
Form input:
<measurements>
<label>
<span>Length</span>
<i ng-show="form.length.$dirty && form.length.$error.required" class="error-icon"></i>
<input type="number" name="length" ng-model="form.length" required placeholder="Length">
</label>
</measurements>
The directive implementation:
angular.module('directive.measurements', [])
.directive('measurements', [function() {
return {
restrict: 'EA',
transclude: true,
templateUrl: 'measurements.html',
scope: {
},
link: function(scope, element, attrs, ctrls) {
scope.focused = false;
var input = element.find('input');
input.on('focus', function(event) {
scope.focused = true;
scope.$apply();
});
input.on('blur', function(event) {
scope.focused = false;
scope.$apply();
});
scope.add = function(amt){
};
}
}
}]);
The template 'measurements.html':
<div>
<span ng-show="focused">
<button class="button button-small" ng-click="add(.125)">+1/8</button>
<button class="button button-small" ng-click="add(.25)">+1/4</button>
<button class="button button-small" ng-click="add(.5)">+1/2</button>
</span>
<span ng-transclude>
</span>
</div>
EDIT After experimenting with the loss of focus issue, I found a workaround by modifying the 'blur' event as shown below. This solution works, but I'm open to better alternatives:
if (event.relatedTarget === null) {
input[0].focus();
} else {
scope.focused = false;
scope.$apply();
}
Edit 2 Here is the plunker: http://plnkr.co/edit/6eUgRhUSA8yI1s42j9JD?p=preview