Toggle edit and display of the fields in a form - angularjs

Above all, I have the plnkr at here.
I am trying to create a series of directive that support in-place toggle of text display and edit within a form. As I understand, there is a similar module like xeditable available, but we need to do something different down the road. So I started with an experiment to start with something similar.
First, I create a directive that allows toggling edit/display by setting an attribute editEnabled on the directive called editableForm. The following code does not do anything special other than a line of log message.
function editableForm ($log) {
var directive = {
link: link,
require: ['form'],
restrict: 'A',
scope: {
editEnabled: "&editEnabled"
}
};
return directive;
function link(scope, element, attrs, controller) {
//$log.info('editEnabled: ' + scope.editEnabled());
$log.info('editEnabled: ' + attrs.editEnabled); //this also works
}
} //editableForm
Then I wrote the following directive to override the input tag in html:
//input directive
function input($log) {
var directive = {
link: link,
priority: -1000,
require: ['^?editableForm', '?ngModel'],
restrict: 'E'
};
return directive;
function link(scope, element, attrs, ngModel) {
ngModel.$render = function() {
if (!ngModel.$viewValue || !ngModel.$viewValue) {
return;
}
element.text(ngModel.$viewValue);
};
$log.info('hello from input');
$log.info('input ngModel: ' + attrs.ngModel);
// element.val('Hello');
scope.$apply(function() {
ngModel.$setViewValue('hello');
ngModel.$render();
});
}
} //input
I was trying to show the ngModel value of the input as text in the input directive, however, it doesn't seem to do anything in my testing. Could someone spot where I am doing wrong? I wish to replace each input fields with text/html (e.g. <span>JohnDoe</span> for Username).
My first attempt on input is a proof of concept. If it works, I will keep working on other tags like button, select, etc.

Long shot here... Your requiring both editableForm and ngModel in your input directive. So the fourth parameter of your link function should be an array of controllers in the respective order of the require array, not the ngModel controller as you are expecting.
I didnt go any further in examining your code, but check it out.

Related

AngularJS $parser not being called when dynamically adding the directive

So what i'm trying to achieve is to be able to add a directive that contains a parser through another directive.
When directly adding the parser directive on an html element it works completely fine. the parser directive i currently use:
.directive('parseTest', [
function () {
return {
restrict: 'A',
require: ['ngModel'],
link: {
post: function (scope, element, attributes, ctrls) {
var controller = ctrls[0];
controller.$parsers.unshift(function (value) {
var result = value.toLowerCase();
controller.$setViewValue(value);
controller.$render();
return result;
})
}
}
}
}
])
Now when i add this directive through another directive the parser never gets called weirdly enough. The directive that generated the parsetest directive:
.directive('generateTest', ['$compile',
function ($compile) {
return {
restrict: 'A',
compile: function (elem, attrs) {
elem.attr('parse-test', '');
elem.removeAttr('generate-test');
var linkFn = $compile(elem);
return function (scope, element, attr) {
linkFn(scope);
}
}
}
}
])
The following works fine:
<input class="form-control col-sm-6" ng-model="model.parsetest" parse-test/>
The following doesn't work (While the generated result html is the same)
<input class="form-control col-sm-6" ng-model="model.generateTest" generate-test />
So my question is how can i get the parser working when it is in a dynamicly added directive?
Note, i already tried the solution to a similar issue from this question, but that doesn't work for me.
EDIT: Here is a plnkr that demonstrates the issue, both fields have the parse-test directive applied to it that should make the value in the model lowercase, but it only works for the one that is not dynamically added as shown in the console logs.
So I've found the solution, so for anyone that stumbles on the same issue here it is.
The 2 small changes have to made to the directive that generates the directive that contains a parser or formatter.
First of set the priority of the directive to a number higher or equal as 1. Secondly put terminal on true. Those 2 settings seem to resolve the issue.
The problem probably lies in that the default execution of nested directives makes it so that the parser and formatters get inserted slightly to late which is why we need to make sure the directive gets generated first thing before anything else.
This is just an assumption of why it works tho, if anyone else has an explanation it would be great :)
As for the code, the directive that generates another directive should look something like:
directive('generateTest', ['$compile',
function ($compile) {
return {
restrict: 'A',
terminal: true,
priority: 1,
compile: function (elem, attrs) {
attrs.$set('parseTest', '');
attrs.$set('generateTest', undefined);
var linkFn = $compile(elem);
return function (scope, element, attr) {
linkFn(scope);
}
}
}
}
])

How to display 4 digits in the TEXT field

I'm using Angular.Js which contains Ionic. I have an
input field with the type as TEXT which contains the maxlength of
16 digits.
Now I want to display the last 4 digits of the field values and other
digits should be masked.
So can anyone please suggest me any approach on it to achieve.
To get you started: First bind the value of the Textarea to a scope variable and add a function for ng-change:
<textarea ng-model="model.myText" ng-change="maskValue()"></textarea>
Then in your controller do something like:
$scope.maskValue = function(){
$scope.model.myText = "xxxxxxxxxxxxxxxx" + $scope.model.myText.substring(16, 20)
}
maskValue() Will be called every time the content of the Textarea changes. This is surely not working "as is" but it should show the right direction.
Use a custom directive to filter the input on change event.
.directive("test", function() {
return {
require: "?ngModel",
scope: {
ngModel: '='
},
link: function(scope, elem, attrs, ngModel) {
elem.bind('change', function() {
console.log(ngModel);
ngModel.$setViewValue(scope.ngModel.substring(scope.ngModel.length - 4, scope.ngModel.length));
ngModel.$render();
});
},
replace: true
}
});
Using scope is not a good idea. It does not offer re-useable module pattern and also has performance issues.

how angular ui typeahead trigger when focus

I'm using angular-ui typeahead. How can I trigger the popup items when focus on the input box, not after typing.
I can attest to the issues associated with expanding the UX of the typeahead. While #ueq's solution works, it has trouble releasing focus/clicking. I suggest changing things, specifically how you trigger the open UX.
suggested changes
open on double click - this solves the issue of click-releasing in #ueq's answer
check for existing values so as not to overwrite the value - we don't want to accidentally overwrite existing data when we open, so check first then set to a non-valid value to trigger the open.
change the name of the directive.... go with something more descriptive - considering that ui.bootstrap has already changed their namespace moving from 13.x to 14.x it just makes sense to go with your own name. Since directives can represent both UI &/or UX, it makes sense to name your directive to something that other developers can later track down more easily.
why
When working with a typeahead, people have certain expectations of the UX. Clicking into an input and having something popup can be somewhat jarring and misdirecting. A single click or tab-focus into an input traditionally does nothing other than readying the input for keyboard interaction. A double click generally carries the expectation that something more will happen (e.g. double click a file & close from a select dialog vs. single click to select, then click "ok" to close).
In programming we often try to employ the separation of concerns paradigm to our code. But I think this could be applied also to this particular UX and UX in general. Let the single-click & tab-focusing do what they've done for years and utilize the double-click to expand the UX of the typeahead.
plunker - http://plnkr.co/edit/GGl6X4klzVLKLX62Itbh?p=preview
.directive('typeaheadClickOpen', function($parse, $timeout) {
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, elem, attrs) {
triggerFunc = function(evt) {
var ctrl = elem.controller('ngModel'),
prev = ctrl.$modelValue || '';
if (prev) {
ctrl.$setViewValue('');
$timeout(function() {
ctrl.$setViewValue(prev);
});
} else {
ctrl.$setViewValue(' ');
}
}
elem.bind('dblclick', triggerFunc);
}
}
})
Hi I had the same issue and with this github discussion I was able to figure it out: Setup a directive that calls $setViewValue like
.directive('typeahead', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ctrl) {
element.bind('click', function () {
ctrl.$setViewValue(' ' );
});
element.bind('blur', function () {
ctrl.$setViewValue('');
});
}
};
});
and add it to your input:
<input type="text" [...] typeahead>
Result (I created a plkr: http://plnkr.co/edit/Si6tFK2AammZy1HqEQzA):
Hope that helps :)
Use typeahead-min-length="0" if supported by your angular-ui version. Otherwise this will help you out:
directive('typeaheadOpenOnFocus', function ($timeout) {
return {
require: 'ngModel',
link: function (scope, element, attr, ctrl) {
element.bind('click', function () {
var vv = ctrl.$viewValue;
ctrl.$setViewValue(vv ? vv+' ': ' ' );
$timeout(function(){ctrl.$setViewValue(vv ? vv : '');},10)
});
}
};
})
and add typeahead-open-on-focus as attribute to your input element.
This will open the typeahead onfocus if it already has a value too.
And it automatically reverts the viewvalue.
Inspired by the answer of Boem
You can try this for avoiding the issue of view rendering
app.directive('typeahead', function () {
return {
restrict: "A",
require: 'ngModel',
link: function (scope, element, attr, ctrl) {
element.bind('click', function () {
ctrl.$setViewValue('');
ctrl.$render();
});
}
};});

Angular - Directive reflecting ngModel array

This is piggy-backing a little off an earlier question. I have been trying to work with directives and data from a model/array
My model looks something like this:
$scope.testModel = {
inputA:[1,2,3]
};
Then I would have inputs for each.
My directive is checking, on keyup, if the input is greater than a given number (10). If it is, then it sets it as 10.
link: function(scope, element) {
scope.$watch('ngModel',function(val){
element.val(scope.ngModel);
});
element.bind("keyup", function(event) {
if(parseInt(element.val())>10){
element.val(10);
scope.ngModel=element.val();
scope.$apply();
}
});
}
The problem is that I get an error, depending on the input:
TypeError: Cannot set property '0' of undefined
Here is the fiddle to see the error and code I have set up: https://jsfiddle.net/prXm3/3/
NOTE
I would prefer not to change the data set as I receive it directly from the server. I know I can change the model to inputA0:1,inputA1:2,inputA2:3 and get it to work, but then I would have to transform the data when my app gets it, and then re-transform it when I send to back to the server. I would prefer to leave the model as I have it set.
Since your directive is interacting with ngModel, you should work along with it in order to update both the model and the view:
angular.module('test', []).directive('myDirective', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return;
ngModel.$parsers.unshift(function(viewValue) {
if(parseInt(viewValue) > 10) {
ngModel.$setViewValue(10);
ngModel.$render();
return 10;
}
else
return viewValue;
});
}
}
});
Working jsFiddle.
Perhaps you'd be interested in checking out the following posts for further information:
NgModelController
Developer's Guide on Forms

How to write an Angular directive for input and contenteditable

my html is taking input in two form, input and contenteditable div . I want to write one directive that handles both, but I cannot find a way to figure out which tag has called the function (because Angular's JQLite doesnt provide a is() or get() function). The following code will be complete if I can figure out to evaluate IS_INPUT_TAG:
function funct() { return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
// view -> model
element.bind('input', function() {
scope.$apply(function() {
if(IS_INPUT_TAG)
ctrl.$setViewValue(element.val());
else
ctrl.$setViewValue(element.text());
scope.watchCallback(element.attr('data-ng-model'));
});
});
// model -> view
ctrl.$render = function() {
if(IS_INPUT_TAG)
element.val(ctrl.$viewValue);
else
element.text(ctrl.$viewValue);
};
}};
}
app.directive('input', funct);
app.directive('contenteditable', funct);
In your directive, you can make use of the element parameter of the linking function to identify the tag on which the directive is applied. You can then use that in your IF condition as follows:
ctrl.$render = function() {
var tagname = element["0"].tagName;
if(tagName === "INPUT")
element.val(ctrl.$viewValue);
else
element.text(ctrl.$viewValue);
};
After, this you can simply attach the directive to the input and the div tags as an attribute to the tags to identify the tag to which the directive is applied.

Resources