string.format a string in AngularJS dynamically - angularjs

I have a translate directive that takes a key and provides the text in the current locale which could be any language.
So for example you can do either:
<p translate="yes">#App.MyString</p>
or
<p>{{'#App.MyString' | translate }}</p>
And it will print in the language of the selected culture.
<p> This is my string </p>
The filter in place to handle translations is:
export class TranslateFilter {
public static build(getTextCatalog: Infrastructure.IGettextCatalog) {
var filter = (resourceKey, resourceType, resourcePrefix) => {
if (resourcePrefix != null) {
resourceKey = `${resourcePrefix}.${resourceKey}`;
}
return getTextCatalog.getString(`#${resourceType}.${resourceKey}`);
};
return filter;
}
}
I want to now also try to combine this with string.Format.
So if the #App.KeyString contains a string like this: 'Hi {0}. Welcome to {1}' I can do a string.Format using dynamic values.
I can do that within the controller but I was wondering if there's a way it could be done on the html file.
For example something like this:
<p translate="yes" format="{{scope.name}},{{scope.place}}">#App.MyString</p>
or
<p>{{'#App.MyString' | translate | format:[$scope.name, $scope.place] }}</p>
would print
'Hi Nick! Welcome to Narnia'
Any ideas?

Related

Is there simple “angularJS” way using ng-repeat directive, to replace characters in object.name string with other character directly?

If the object's property name is Bob_Kenneth_Frank (as actual value) to Bob Kenneth Frank (displayed output)
I unsuccessfully tried different variants of:
html
ng-repeat="myChange(person.name) in persons"
in controller
function myChange(name){
return name.replace(/_/g, " ")
}
Use a custom filter.
See a working demo.
angular.module('app').filter('replaceUnderscoreBySpace', function () {
return function (input) {
return input.replace(/_/g, ' ');
};
});
View:
<div ng-repeat="x in y">
{{x | replaceUnderscoreBySpace}}
</div>
Explanations on Todd Motto Blog

Dynamic checkbox from list with Thymeleaf

I try to save the values from dynamically created checkboxes:
<div>
<ul>
<li th:each="item, stat : *{users}">
<input type="checkbox" th:field="*{users[__${stat.index}__]}" th:value="${item}" />
<label th:text="${item}"></label>
</li>
</ul>
</div>
The controller provides the String items as follwing:
public List<String> getUsers() {
return users;
}
And the setter for the Strings is:
public void setUsers(final String[] users) {
for (final String string : users) {
System.out.println(string);
}
}
The values are correct shown in the html page. But when i click save button, and the setter is called, the values are empty. What can i do, where is the problem?
Any help would appreciate.
Please check out section about handlin multi-value checkboxes in Tutorial: Thymeleaf + Spring.
You should provide some model attribute (of type List<String>) containing all users possible to select. Let's call it selectableUsers.
Then it can collaborate with your form-backing bean (that one containing users) in a following manner:
<div>
<ul>
<li th:each="item : ${selectableUsers}">
<input type="checkbox" th:field="*{users}" th:value="${item}" />
<label th:for="${#ids.prev('users')}" th:text="${item}"></label>
</li>
</ul>
</div>
Note I think that getter and setter for a field should handle the same type, but they don't (getter returns List<String> however setter consumes String[])
What you are trying to do looks logical, but it does not work that way.
If you did not get it resolved you can do this instead:
In relevant method of your controller you can add list of titles for your checkboxes:
List<String> allUsers = Arrays.asList("abc","xyz"); // OR generate list dynamically
model.addAttribute("selectableUsers", allUsers);
Or add it to ModelAndView if that is what you are using.
Change your html to what was suggested by #Jakub Ch.
Change your getter and setter methods as follows:
private String users;
...
public String getUsers() {
return this.users;
}
public void setUsers(String users) {
this.users = users;
}
Then 'users' field will contain comma separated String values or their id numbers ( depending on how you set it up) indicating selected checkboxes. Then you can convert String values to array using code like below or if id numbers are stored get String values from your ArrayList.
public List<String> getStrings() {
return Arrays.asList(strings.split(","));
}
Hope it helps.

Pass variable to component view to be used as filter

I've build a simple component that allows passing a filter as a parameter, and I'm trying to use that parameter in the component view, but I don't know how. It gets passed as a string so it's treated as a string in the component view and thus not working.
Basically it looks something like this:
<number-compare value="some.value" filter="currency"/>
And in the component view:
<span> {{ numCompCtrl.value | numCompCtrl.value.filter }} </span>
But that doesn't work because it gets interpreted as {{ 10 | "currency" }}
I've tried to handle it in the controller instead, and apply the filter there but it gets really messy when the filter needs multiple parameters so the easiest thing by far would be if I could get the simple way working.
Is it possible?
Actually, I just discovered that I had already solved this previously with another filter as a workaround 🙈
(function() {
'use strict';
angular
.module('core')
.filter('dynamic', dynamic);
dynamic.$inject = ['$interpolate'];
function dynamic($interpolate) {
return function(value, name) {
if (!name) {
return value;
}
var result = $interpolate('{{ value | ' + name + ' }}');
return result({ value: value });
};
}
})();
And used like this:
{{ numCompCtrl.value | dynamic: numCompCtrl.value.filter }}

How to translate the content of an attribute with angular-translate

in my mongo schema i have an enum with predefined types:
let MeterSchema = new Schema({
[...]
type: {
type: String,
enum: ['Prepayment', 'TimeOfDay', 'PowerExport']
},
[...]
}
What i want is to display this value internationalized with i18n files on my angular view.
I looked at the Variale replacement of angular translate (https://angular-translate.github.io/docs/#/guide/06_variable-replacement), but could not figure it out how do it properly with this.
At the moment i translate it that way:
View
<div class="md-summary">{{vm.getMeterType(meter) | translate}}</div>
Controller
public getMeterType(meter): String {
return 'app.masterData.meters.type.' + meter.type;
}
But i think there has to be a better way to this.
The answer is actually pretty simple:
<div class="md-summary">{{'app.masterData.meters.type.' + meter.type | translate}}</div>
I don't know why i didn't use string concatenation in the first place.

AngularJS - Can't use filter to set variable in view

I'm using a filter to calculate values, but then I want to access them later on.
Here's a snippet of my code:
app.controller('CreateProposalCtrl', function() {
$scope.EstimatedCostItem = [];
});
-
app.filter('EstimatedValue', function() {
return function(input, arguments) {
...blah blah calculations
return calculations;
};
});
I'm not sure how the HTML should be presented.
This displays exactly what I want..BUT I need it to set a variable so I can access it somewhere else..
<span ng-repeat="foo in bar">
{{ Type.JobTypeID | EstimatedValue: form }}
</span>
I've tried:
<span ng-model="EstimatedCostItem[Type.JobTypeID]" ng-bind="Type.JobTypeID | EstimatedValue: form"></span>
And:
<span ng-bind="EstimatedCostItem[Type.JobTypeID]">{{ Type.JobTypeID | EstimatedValue: form }}</span>
And:
<span ng-init="EstimatedCostItem[Type.JobTypeID] = (Type.JobTypeID | EstimatedValue: form)"></span>
Nothing seems to set a variable. I'm stumped :(
The filter syntax only works within specific Angular expressions. Expressions that use plain JavaScript cannot use the foo | bar filter syntax, as it's not valid JavaScript.
What you could do is use $filter:
var value = $filter('EstimatedValue')(foo);
Remember to inject $filter into your controller.
With that said, this probably isn't the best use of a filter. Why not create a scope function that calculates and stores the value? Something like:
$scope.EstimatedValue = function(foo) {
var value = doSomeCalculations();
// store for usage elsewhere
this.estimatedValuesCache[foo] = val;
return val;
};

Resources