将显示值格式传递给 angular 组件

Passing display value format to angular component

我想将显示值的格式传递给 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']

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

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

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>