Reputation: 428
I would like to pass the formatting of a display value to an angular component.
For example:
format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)'
or
format="'(tz, offset) location'" === '(EDT -04:00) New York'
The idea is that the value will be displayed as per the format given, parentheses included. I'm guessing the best way to acheive this would be to have an array of the format required? So given the following string, how can I generate the following array:
'(utc, offset) location (tz)' === ['(', 'utc-code', 'offset-hours', ')', 'location', '(', 'tz-code', ')'];
'(tz, offset) location' === ['(', 'tz', 'offset', ')', 'location']
Upvotes: 0
Views: 777
Reputation: 2294
You can use component binding
to pass the value. Here $doCheck
will be called in each digest cycle which provides an opportunity to detect and act on changes to the bindings.
I have written a simple logic with regular expression to display the data with input format. Hope this approach would helps instead of your array approach.
angular.module('app',[])
.controller('appCtrl', function($scope){
$scope.format = '(offset) location (tz)';
})
.component('myComponent', {
template: '<div>{{$ctrl.formattedValue}}</div>',
controller: myComponentCtrl,
bindings: {
format: '='
}
});
function myComponentCtrl(/*your DI goes here*/){
console.log('log from component: format->'+this.format);
var self = this;
this.formattedValue = '';
this.$doCheck = function(){
var sampleDateObject = {
tz: 'CDT',
offset: '-4:00',
location: 'Chicago',
year: 2017
}
self.formattedValue = self.format.replace(/([a-z]+)/gi, function(match){
return sampleDateObject[match]?sampleDateObject[match]:match;
});
};
}
myComponentCtrl.$inject = [/*your DI goes here as string*/];
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.min.js"></script>
<div ng-app="app" ng-controller="appCtrl">
<my-component format="format"></my-component>
<my-component format="'(tz, offset) location, year'"></my-component>
</div>
Upvotes: 2