【问题标题】:Passing display value format to angular component将显示值格式传递给角度组件
【发布时间】:2017-03-30 13:44:56
【问题描述】:

我想将显示值的格式传递给角度组件。

例如:

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']

【问题讨论】:

  • 创建一个custom date filter
  • 您使用的是哪个组件?是你的代码吗?请张贴它的骨架
  • 这是一个自定义组件,显示时区列表。这个想法是让组件用户能够指定显示值的格式。
  • 您需要编写逻辑来格式化显示值还是已经写在组件中?是角1吗? - 组件或指令?还是角度 2?
  • 这是一个角 1 组件。也许一开始我只需要练习如何将字符串 '(utc, offset) location (tz)' 转换为看起来像 ['(', 'utc-code', 'offset-hours', ')' 的数组, 'location', '(', 'tz-code', ')'],因为我很清楚在那之后该怎么做。

标签: javascript angularjs regex string formatting


【解决方案1】:

您可以使用组件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>

【讨论】:

  • 这个替换功能正是我所追求的。非常感谢您花时间回答我措辞不当的问题。
猜你喜欢
  • 2019-04-02
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
  • 2021-10-17
  • 2023-04-10
相关资源
最近更新 更多