gpt4 book ai didi

javascript - 将显示值格式传递给 Angular 分量

转载 作者:行者123 更新时间:2023-12-01 03:51:46 24 4
gpt4 key购买 nike

我想将显示值的格式传递给 Angular 分量。

例如:

format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)'

format="'(tz, offset) location'" === '(EDT -04:00) New York'

这个想法是,该值将按照给定的格式显示,包括括号。我猜实现这一目标的最佳方法是拥有所需格式的数组?因此,给定以下字符串,如何生成以下数组:

'(utc, offset) location (tz)' === ['(', 'utc-code', 'offset-hours', ')', 'location', '(', 'tz-code', ')'];

'(tz, offset) location' === ['(', 'tz', 'offset', ')', 'location']

最佳答案

您可以使用组件绑定(bind)来传递值。这里 $doCheck 将在每个摘要周期中调用,这提供了检测绑定(bind)更改并对其采取行动的机会。

我用正则表达式编写了一个简单的逻辑来显示输入格式的数据。希望这种方法能够代替您的数组方法有所帮助。

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>

关于javascript - 将显示值格式传递给 Angular 分量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43119750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com