Is it possible to add angularized html tags and attributes in a directive based on model data in Angularjs? - forms

I want to build a directive that will build form inputs based on a nested object of settings that include the input type, model to bind, and html attributes. I have been pounding my head and, perhaps, am close to concluding that this is something Angular is not equipped to do. I would like to build a directive that could take an array of objects like:
[{
"label":"When did it happen",
"model": $scope.event.date,
"element":"input",
"type": "date",
"options":{
"class":"big",
"required": true,
},
},{
"label":"How did it happen?",
"model": $scope.event.cause,
"element":"textarea",
"options":{
"cols":45,
"rows":55,
},
},{
"label":"How many times did it happen?",
"model": $scope.event.times,
"element":"input",
"options":{},
}],
I have struggled through many different aspects of directives. I keep running across a few issues.
Neither the template nor the controller directive functions have access to any sort of scope that could reach any sort of data--most especially my array I've made. This means that I can't decide how to build my DOM (i.e. tag types and attributes) until later.
All compiling is done before the linking function. I am able to manipulate the DOM in the linking function but none of it is angularized. This means if I add a required attribute angular's ngValidate is not aware of it. If I try and change the tag type, I reset lose my model binding etc.
It seems that this is just the way angular runs. Is there no good way to affect the DOM tag types and attributes based on model data without specifying everything out specifically?

How about something like this:
$scope.event = {
date: new Date(),
cause:'It was the colonel in the kitchen with the revolver',
time:5, //...
$metadata: data
};
Where data here is simply the array you have already shown. (apart from the model property which would just be a string representing the property of the event, like so:
{
"label":"When did it happen",
"model":'date',
"element":"input",
"type": "date",
"options":{
"class":"big",
"required": true,
}
}
Then your directive would simply access the property given it on the parent scope. (event) And process the metadata into a usable template. Which could then get compiled.
Here is such a directive, and the directive...
myApp.directive('contentForm',function($compile,$interpolate){
var template = "<span class='lbl'>{{label}}</span><{{element ||'input'}} {{options}}"+
" ng-model='{{root+'.'+model}}'></{{element}}>";
function linkerFunction(scope,element,attrs){
if(!scope[attrs.contentForm])return;
var metadata = scope[attrs.contentForm].$metadata || false;
if(!metadata)return;
element.html(getHtml(metadata,attrs.contentForm));
$compile(element.contents())(scope);
}
return {
restrict: 'A',
replace: true,
link:linkerFunction
};
//interpolate the template with each set of metadata
function getHtml(metadata,root){
var interpolation = $interpolate(template);
var html = '';
if(angular.isArray(metadata)){
for(var i = 0; i < metadata.length; i++){
metadata[i].root = root;
metadata[i].options = processOptions(metadata[i].options);
html += interpolation(metadata[i]) + '</br>'
}
}else{
html = interpolation(metadata);
metadata.options = processOptions(metadata.options);
}
return html;
}
// parse object into html attributes
function processOptions(options){
var result = '';
for(var key in options){
if(options.hasOwnProperty(key)){
result += ' '+key+"='"+options[key]+"'"
}
}
return result.trim();
}
});
You'd probably want to change the template. I seem to have forgotten to put in a type. But that should be fairly straight forward. I hope this helps!

Related

Adding data to map without overwriting - Dart

I have multiple maps inside maps, such as:
Program = {'day0': {'area0': {'exercise0': 'value'}}, 'day1': {'area0': {'exercise0': 'value'}}};
And, I want to add data to 'exercise0'. But, sometimes previous data will not be set. Such as creating 'area0' without setting 'day1'.
So...
Program['day0']['area0']['exercise0'] = 'failure';
...this code doesn't work, because 'area0' is not set.
I have used addAll too:
Program.addAll({
'day${dayIndex}': {
"area0": {
'area': Chest,
'exercise0': {'exercise': Chest.exercises[0]},
},
"area1": {
'area': FrontArm,
'exercise0': {'exercise': FrontArm.exercises[0]},
}
},
});
But rn this one overwrites the existing values.

xPages REST Service Results into Combobox or Typeahead Text Field

I've read all the documentation I can find and watched all the videos I can find and don't understand how to do this. I have set up an xPages REST Service and it works well. Now I want to place the results of the service into either a combobox or typeahead text field. Ideally I would like to know how to do it for both types of fields.
I have an application which has a view containing a list of countries, another view containing a list of states, and another containing a list of cities. I would like the first field to only display the countries field from the list of data it returns in the XPages REST Service. Then, depending upon which country was selected, I would like the states for that country to be listed in another field for selection, etc.
I can see code for calling the REST Service results from a button, or from a dojo grid, but I cannot find how to call it to populate either of the types of fields identified above.
Where would I call the Service for the field? I had thought it would go in the Data area, but perhaps I've just not found the right syntax to use.
November 6, 2017:
I have been following your suggestion, but am still lost as can be. Here's what I currently have in my code:
x$( "#{id:ApplCountry}" ).select2({
placeholder: "select a country",
minimumInputLength: 2,
allowClear : true,
multiple: false,
ajax: {
dataType: 'text/plain',
url: "./Application.xsp/gridData",
quietMillis: 250,
data: function (params) {
return {
search:'[name=]*'+params.term+'*',
page: params.page
};
},
processResults: function (data, page) {
var data = $.map(data, function (obj) {
obj.id = obj.id || obj["#entityid"];
obj.text = obj.text || obj.name;
return obj;
});
},
return {results: data};
}
}
});
I'm using the dataType of 'text/plain' because that was what I understood I should use when gathering data from a domino application. I have tried changing this to json but it makes no difference.
I'm using processResults because I understand this is what should be used in version 4 of select2.
I don't understand the whole use of the hidden field, so I've stayed away from that.
No matter what I do, although my REST service works if I put it directly in the url, I cannot get any data to display in the field. All I want to display in the field is the country code of the document, which is in the field named "name" (not my choice, it's how it came before I imported the data from MySQL.
I have read documentation and watched videos, but still don't really understand how everything fits together. That was my problem with the REST service. If you use it in Dojo, you just put the name of the service in a field on the Dojo element and it's done, so I don't understand why all the additional coding for another type of domino element. Shouldn't it work the same way?
I should point out that at some points it does display the default message, so it does find the field. Just doesn't display the country selections.
I think the issue may be that you are not returning SelectItems to your select2, and that is what it is expecting. When I do something like you are trying, I actually use a bean to generate the selection choices. You may want to try that or I'm putting in the working part of my bean below.
The Utils.getItemValueAsString is a method I use to return either the string value of a field, or if it is not on the document/empty/null an empty string. I took out an if that doesn't relate to this, so there my be a mismatch, but I hope not.
You might be able to jump directly to populating the arrayList, but as I recall I needed to leverage the LinkedHashMap for something.
You should be able to do the same using SSJS, but since that renders to Java before executing, I find this more efficient.
For label/value pairs:
LinkedHashMap lhmap = new LinkedHashMap();
Document doc = null;
Document tmpDoc = null;
allObjects.addElement(doc);
if (dc.getCount() > 0) {
doc = dc.getFirstDocument();
while (doc != null) {
lhmap.put(Utils.getItemValueAsString(doc, LabelField, true), Utils.getItemValueAsString(doc, ValueField, true));
}
tmpDoc = dc.getNextDocument(doc);
doc.recycle();
doc = tmpDoc;
}
}
List<SelectItem> options = new ArrayList<SelectItem>();
Set set = lhmap.entrySet();
Iterator hsItr = set.iterator();
while (hsItr.hasNext()) {
Map.Entry me = (Map.Entry) hsItr.next();
// System.out.println("after: " + hStr);
SelectItem option = new SelectItem();
option.setLabel(me.getKey() + "");
option.setValue(me.getValue() + "");
options.add(option);
}
System.out.println("About to return from generating");
return options;
}
I ended up using straight up SSJS. Worked like a charm - very simple.

approach for validated form controls in AngularJS

My teammates and I are learning AngularJS, and are currently trying to do some simple form field validation. We realize there are many ways to do this, and we have tried
putting input through validation filters
using a combination of controller and validating service/factory
a validation directive on the input element
a directive comprising the label, input and error output elements
To me, the directive approach seems the most "correct". With #3, we ran into the issue of having to communicate the validation result to the error element (a span sibling). It's simple enough to do some scope juggling, but it seemed "more correct" to put the span in the directive, too, and bundle the whole form control. We ran into a couple of issue, and I would like the StackOverflow community's input on our solution and/or to clarify any misunderstandings.
var PATTERN_NAME = /^[- A-Za-z]{1,30}$/;
module.directive("inputName", [
function () {
return {
restrict: "E",
require: "ngModel",
scope: {
fieldName: "#",
modelName: "=",
labelName: "#",
focus: "#"
},
template: '<div>' +
'<label for="{{fieldName}}">{{labelName}}</label>' +
'<input type="text" ng-model="modelName" id="{{fieldName}}" name="{{fieldName}}" placeholder="{{labelName}}" x-blur="validateName()" ng-change="validateName()" required>' +
'<span class="inputError" ng-show="errorCode">{{ errorCode | errorMsgFltr }}</span>' +
'</div>',
link: function (scope, elem, attrs, ngModel)
{
var errorCode = "";
if (scope.focus == 'yes') {
// set focus
}
scope.validateName = function () {
if (scope.modelName == undefined || scope.modelName == "" || scope.modelName == null) {
scope.errorCode = 10000;
ngModel.$setValidity("name", false);
} else if (! PATTERN_NAME.test(scope.modelName)) {
scope.errorCode = 10001;
ngModel.$setValidity("name", false);
} else {
scope.errorCode = "";
ngModel.$setValidity("name", true);
}
};
}
};
}
]);
used as
<form novalidate name="addUser">
<x-input-name
label-name="First Name"
field-name="firstName"
ng-model="firstName"
focus="yes"
model-name="user.firstName">
</x-input-name>
<x-input-name
label-name="Last Name"
field-name="lastName"
ng-model="lastName"
model-name="user.lastName">
</x-input-name>
...
</form>
First, because both form and input are overridden by AngularJS directives, we needed access to the ngModel API (ngModelController) to allow the now-nested input to be able to communicate validity to the parent FormController. Thus, we had to require: "ngModel", which becomes the ngModel option to the link function.
Secondly, even though fieldName and ngModel are given the same value, we had to use them separately. The one-way-bound (1WB) fieldName is used as an attribute value. We found that we couldn't use the curly braces in an ngModel directive. Further, we couldn't use a 1WB input with ngModel and we couldn't use a two-way-bound (2WB) input with values that should be static. If we use a single, 2WB input, the model works, but attributes like id and name become the values given to the form control.
Finally, because we are sometimes reusing the directive in the same form (e.g., first name and last name), we had to make attributes like focus parameters to be passed in.
Personally, I would also like to see the onblur and onchange events bound using JavaScript in the link function, but I'm not sure how to access the template markup from within link, especially outside/ignorant of the larger DOM.

concatenating jQuery objects

Below is the prototype of what I am trying to do.
var entry_set = $;
// start to loop data
for([])
{
// create HTML element to represent that data
$('<div></div>')
.data([])
.addClass([])
.on([])
.insertAfter(entry_set);
}
// modify DOM only once all the entries are consolidated to a single jQuery object
entry_set.appendTo('.entries');
The comments say it all. In short - the idea is to modify document DOM only once when inserting data. I would usually go HTML string approach (simply concatenating the same structure using a string), but I am interested whether anything similar to this might work as well.
You could create an empty DOM element and .append() to that
var entry_set = $("<div>"); //empty dom element
// start to loop data
var i = 4;
while(i--) {
// create HTML element to represent that data
var item = $('<div>', {
text: "test " + i
});
entry_set.append(item);
}
// modify DOM only once all the entries are consolidated to a single jQuery object
$("body").append(entry_set.children());​
working demo at: http://jsfiddle.net/F2J6g/1/
EDIT
You can also start with an empty collection and use .add()
var entry_set = $(); //empty collection
// start to loop data
var i = 4;
while(i--) {
// create HTML element to represent that data
var item = $('<div>', {
text: "test " + i
});
entry_set = entry_set.add(item);
}
// modify DOM only once all the entries are consolidated to a single jQuery object
$("body").append(entry_set);
http://jsfiddle.net/F2J6g/2/
#Guy, I don't think you will get the desired HTML output. try using "wrap".
Sample Syntax:
$('.OuterDiv').wrap('<div class="abc" />');
Unfortunately, because those objects aren't actually attached to any heirarchy, calling insertAfter doesn't actually mean anything. What you'll need to do is put them inside a containing div, maybe something like this:
var entry_set = $('<div>');
// start to loop data
for([])
{
// create HTML element to represent that data
$('<div></div>')
.data([])
.addClass([])
.on([])
.appendTo(entry_set);
}
// modify DOM only once all the entries are consolidated to a single jQuery object
entry_set.appendTo('.entries');
I haven't tested that, but I think it should work.

jqgrid edittype select load value from data

I am using jqgrid in my new project.
In a specific case I need to use a select element in the grid. No problem.
I define the colModel and the column for example like (from wiki)
colModel : [
...
{name:'myname', edittype:'select', editoptions:{value:{1:'One',2:'Two'}} },
...
]
But now when I load my data I would prefer the column "myname" to contain the value 1.
This won't work for me instead it has to contain the value "One".
The problem with this is that the text-part of the select element is in my case localized in the business layer where the colModel is dynamically generated. Also the datatype for the entity which generates the data via EF 4 may not be a string. Then I have to find the correct localized text and manipulate the data result so that the column "myname" does not containt an integer which is typically the case but a string instead with the localized text.
There is no option you can use so that when the data contains the value which match an option in the select list then the grid finds that option and presents the text.
Now the grid presents the value as a text and first when I click edit it finds the matching option and presents the text. When I undo the edit it returns to present the value again.
I started to think of a solution and this is what I came up with. Please if you know a better solution or if you know there is a built in option don't hesitate to answer.
Otherwise here is what I did:
loadComplete: function (data) {
var colModel = grid.getGridParam('colModel');
$.each(colModel, function (index, col) {
if (col.edittype === 'select') {
$.each(grid.getDataIDs(), function (index, id) {
var row = grid.getRowData(id);
var value = row[col.name];
var editoptions = col.editoptions.value;
var startText = editoptions.indexOf(value + ':') + (value + ':').length;
var endText = editoptions.indexOf(';', startText);
if (endText === -1) { endText = editoptions.length; }
var text = editoptions.substring(startText, endText);
row[col.name] = text;
grid.setRowData(id, row);
});
}
});
}
It works and I will leave it like this if nobody comes up with a better way.
You should just include additional formatter:'select' option in the definition of the column. See the documentation for more details.