Polymerjs object bracket notation and data binding - polymer-1.0

When I am trying to bind data to an object property with bracket notation, it does not work
{{myObj[variable]}}
So I created a function
_convertObj(variable){
return this.myObj[variable];
}
then displaying the data works with below code
{{_convertObj(variable)}}
but for two way data binding to work if I use the below code it doesn't work
<input type="text" value="{{_convertObj(variable)::input}}" />
Is there a standard way of doing this which I am unable locate in documentation?

I think I have solved it myself by using computed binding
<input type="text" name="{{variable}}" value="{{_computeObjData(formData.*,variable)}}" on-input="_changeData" />
_computeFormData: function(formDataChange, name) {
return formDataChange.base[name];
},
_changeData: function(e){
this.set('formData.'+[e.target.name], e.target.value);
}

Related

AngularJS doesnt show the value of object's property

this should be straight forward, just cant figure out why it's not working.
I receive data in this format from Web API 2 (captured from Chrome's debugger):
AngularJS code to render the results
(vm.reportParameters contains that structure on the screenshot with 2 nodes):
<form>
<div ng-repeat="param in vm.reportParameters" class="form-group">
<label>Name</label>
<input type="text" class="form-control" value="{{param.Name}}" />
</div>
</form>
The output (missing value of Name property, should display "Country"):
Any idea what I am missing here? Why the value is not shown?
// GET api/reports/5
// This action retrieves parameters of selected report by reportId
[ResponseType(typeof(ParametersModel))]
public IHttpActionResult Get(string reportId)
{
try
{
var manager = new ReportsManager();
var model = manager.GetReportParameters(reportId);
if (model == null || model.Parameters == null || model.Parameters.Count == 0)
{
return NotFound();
}
return Ok<ParametersModel>(model);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
Thanks.
UPDATE
This garbage-alike data has this weird format with all these k__XXXXX
things because I had various attributes applied to the model for XML
Deserialization (in C# code). After I removed all these Serialization
attributes, the model became normal and clean as expected. Go guess :)
Use without expression, ng-model
<input type="text" class="form-control" ng-model="param.Name" />

Dynamic hidden fields values where model name is stored in database

I have a requirement in angular js application where I need to dynamically create hidden variables. Name and value attribute for these hidden fields will be from database. But rather than storing actual value of hidden field in database name of model is stored in a database.
I have written a test function as follows. TempVars will be from database but for time being I have hard coded few values.
$rootScope.populate = function () {
$rootScope.models = {
MyModel: {}
};
$rootScope.models.MyModel.Client = [];
$rootScope.models.MyModel.Client.FirstName = 'FName';
$rootScope.models.MyModel.Client.LastName = 'LName';
$rootScope.TempVars = [
{"key":"var-FirstName","value":"{{models.MyModel.Client.FirstName}}"},
{ "key": "var-LastName", "value": "{{models.MyModel.Client.LastName}}" },
]
};
Following is my HTML code
<input type="hidden" ng-repeat="obj in TempVars" name="{{obj.key}}" value="{{obj.value}}" />
<input type="text" ng-repeat="obj in TempVars" name="{{obj.key}}" value="{{obj.value}}" />
<input type="hidden" name="test" value="{{models.MyModel.Client.FirstName}}" />
I am expecting that hidden filed value should have FName and LName in it. But rather it contains {{models.MyModel.Client.FirstName}} and {{models.MyModel.Client.LastName}} in it. Whereas variable name with name test has FName value stored in it.
Is is possible to achieve this in angularjs?
It won't work that way in angularjs but you will be able to do that through a custom directive and using NGModelController to $format and $parse the data.
Here are some links where you can get the idea about that :
https://egghead.io/lessons/angularjs-using-ngmodel-in-custom-directives
http://radify.io/blog/understanding-ngmodelcontroller-by-example-part-1/

Post full form data to a service in Angular

I have a form that contains a lot of fields and I want to post all the form fields to a service using a post method. But I would like to send the whole form object and not to write one property by one. If I try to post the object that contains all my fields $scope.formData it also contains all the angular stuff inside like errors. What I need is a collection of field names and values. How can I achieve this with minimum coding?
Edit:
I ended up writing my own function:
function getAngularFormFields(form) {
var dictionary = { form: {} };
for (var key in form) {
if (form.hasOwnProperty(key) && !key.indexOf('$') == 0) {
dictionary.form[key] = form[key].$modelValue;
}
}
return dictionary;
}
Normally if you need to post a form you could just use the default method provided by your browser. This will send the form data, via POST, to your URL.
<form action="yourUrlHere" method="POST">
First name: <input type="text" name="fname">
Last name: <input type="text" name="lname">
<input type="submit" value="Submit">
</form>

How to pass an array of checkboxes to a knockout custom binding?

i'm using knockout 2.2.1.
I have a set of 3 check boxes to concatenate to get the corresponding values all together:
<fieldset data-role="controlgroup" id="top-colours" data-bind="topColoursLabel: { topColoursRed,topColoursBlue,topColoursGreen }">
<legend>Top Colours:</legend>
<input type="checkbox" name="top-colours-red" data-bind="checked: topColoursRed" id="tc-check-1" />
<label for="tc-check-1">Red stripes</label>
<input type="checkbox" name="top-colours-blue" data-bind="checked: topColoursBlue" id="tc-check-2" />
<label for="tc-check-2">Blue stripes</label>
<input type="checkbox" name="top-colours-green" data-bind="checked: topColoursGreen" id="tc-check-3" />
<label for="tc-check-3">Green stripes</label>
</fieldset>
The result shall be for example: "Red stripes, Blue stripes".
My viewmodel is as follows:
function ColoursViewModel() {
var self = this;
self.template = "coloursView";
self.topColoursRed = ko.observable(false);
self.topColoursBlue = ko.observable(false);
self.topColoursGreen = ko.observable(false);
self.topColoursDescription = ko.observable("");
}
How shall be the custom bindings to achieve this?
I try something like that:
ko.bindingHandlers.topColoursLabel = {
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
ko.utils.unwrapObservable(valueAccessor());
// ...
var checkText = '...';
viewModel.topColoursDescription(checkText);
}
};
I'm not able to find out how to pass the array to my custom bindings to subscribe to the values of the 3 check boxes, because I'm noob to knockout.
It seems to me, that a declaration like:
data-bind="topColoursLabel: { topColoursRed,topColoursBlue,topColoursGreen }"
would be great to achieve this, but i'm searching the right way to do that.
Note: i cannot use a computed observable here, because i need to get some other properties from element - i mean the label-for text - so a custom binding is needed.
Can someone help?
UPDATED jsFiddle: http://jsfiddle.net/Sx87j/
Actually, custom binding handler is not what you really need. You should implement your self.coloursDescription as computed observable which will track checkbox changes and return currently selected stripes:
self.topColoursDescription = ko.computed(function(){
var colors = [];
if (self.topColoursRed()) colors.push('Red stripes');
if (self.topColoursBlue()) colors.push('Blue stripes');
if (self.topColoursGreen()) colors.push('Green stripes');
return colors.join(', ');
});
Also remove all tracks of your custom bindings from markup and you will get something like this: http://jsfiddle.net/h7Bmb/8/
Update
I can make your updated fiddle to work with top colours. Making it work with bottom colors too looks a bit complicated with your current approach.
Enumerate all linked color observables in your binding:
<fieldset data-role="controlgroup" id="top-colours" data-bind="topColoursLabel: [ topColoursRed, topColoursBlue, topColoursGreen ]">
Change your custom binding code (the line where ko.utils.unwrapObservable is called):
ko.utils.arrayForEach(valueAccessor(), ko.utils.unwrapObservable);
Example: http://jsfiddle.net/Sx87j/1/

Use checkboxes in angularjs to manage array of objects

I had asked a question about
How to associate objects as models using ng-options in angularjs.
And I got an awesome answer very fast. My followup questions is that the response uses <select mutiple> to handle the child object array.
You can see a working example of what I want, working with <select> at http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=preview
How can I use <input type='checkbox'> (instead of <select>) to handle that object array i.e. ng:model="shirt.colors" while repeating the items from colors object array.
The reason, this appears so complicated to me is that I have to manage an array of objects instead of array of values... for example, if you look in the fiddle, there are color objects and shirt object that has multiple colors.
If the color object changes, it should change the corresponding color objects in shirt objects.
Thank you in advance.
You just need some intermediate value in your scope, and bind checkboxes to it. In your controller - watch for it changes, and manually reconstruct shirt.colors, according to it value.
<div ng-repeat='shirt in shirts'>
<h3>Shirt.</h3>
<label>Size: <input ng-model='shirt.size'></label><br/>
<label>Colors:</label>
<label ng-repeat="color in colors">
{{color.label}} <input ng-model="selection[$parent.$index][$index]" type="checkbox"/>
</label>
</label>
</div>
And in your controller:
$scope.selection = [[],[]];
$scope.$watch('selection', function () {
console.log('change', $scope.selection);
angular.forEach($scope.selection, function (shirtSelection, index) {
$scope.shirts[index].colors = [];
angular.forEach(shirtSelection, function (value, index2) {
if (value) $scope.shirts[index].colors.push($scope.colors[index2]);
});
});
}, true);
You can test it here: http://plnkr.co/edit/lh9hTa9wM5fkh3nT09RJ?p=preview

Resources