AngularJS : 测试是否存在来自 api 端的变量

AngularJS : test if variable exist coming from api side

我有来自 api 端的 json 元数据对象包含一些 属性 图像,我想测试 属性 是否存在,我'我正在使用 angularJS 以及 coffeescript 和 haml 来获取视图。

这里是获取数据的js代码:

getImages = ->
    listImage = []

    for sheet in $scope.report.report_sheets()
      for composed in sheet.report_fragments()
        for fragment in composed.report_fragments()
          if fragment.fragment_type is 'images'
            for media in fragment.media()
              if media.metadata.date_time_original
                media.metadata.date_time_original = moment.utc(media.metadata.date_time_original).local().format('DD-MMM-YYYY h:mm A')
              listImage.push media
    listImage

这里是 haml 面:

.directive-report-images{ ng_show: 'conditionIsChecked && fragment._parentConditionChecked' }
  .row
    .col-md-4
      .title
        %h5.black {{ fragment.title }}
    .col-md-8
      %report_fragment_visibility
      .row{ ng_if: 'fragment.media().length <= 2' }
        .col-md-6.thumbnail{ ng_repeat: "img in fragment.media() | notArchived | orderBy:'order'" }
          %img.pointer{ ng_src: "{{ img.contentUrl() }}", ng_click:'openCarouselModal(img)' }
          %p {{ img.comment }}
          .photo-date{ng_if: "img.metadata.date_time_original" }
            %p {{ img.metadata.date_time_original}}

  .row{ ng_if: 'fragment.media().length > 2' }
    .col-md-12
      .row
        .col-md-4.thumbnail{ ng_repeat: "img in fragment.media() | notArchived | orderBy:'order'" }
          %img.pointer{ ng_src: "{{ img.contentUrl() }}", ng_click:'openCarouselModal(img)' }
          %p {{ img.comment }}
          %p.photo-date {{ img.metadata.date_time_original }}

我想测试 media.metadata.date_time_original 是否存在而不是 null !

我的控制台出现这个错误:

TypeError: Cannot read property 'date_time_original' of null

您需要使用它进行检查,即检查 media.metadata 是否存在,然后继续。

您当前的代码:

getImages = ->
    listImage = []

    for sheet in $scope.report.report_sheets()
      for composed in sheet.report_fragments()
        for fragment in composed.report_fragments()
          if fragment.fragment_type is 'images'
            for media in fragment.media() 
                media.metadata.date_time_original = moment.utc(media.metadata.date_time_original).local().format('DD-MMM-YYYY h:mm A')
              listImage.push media
    listImage

更改为:

getImages = ->
    listImage = []

    for sheet in $scope.report.report_sheets()
      for composed in sheet.report_fragments()
        for fragment in composed.report_fragments()
          if fragment.fragment_type is 'images'
            for media in fragment.media() 
                if (media.metadata) { // check here
                  media.metadata.date_time_original = moment.utc(media.metadata.date_time_original).local().format('DD-MMM-YYYY h:mm A')
                  listImage.push media
                 }
    listImage