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

时间:2018-05-09 12:28:42

标签: angularjs momentjs haml

我有来自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 以显示它是否存在,如果存在则不显示!

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

  

TypeError:无法读取null的属性'date_time_original'

1 个答案:

答案 0 :(得分:1)

您需要使用它进行检查,即检查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