将ng-token-auth与typeahead / bloodhound一起使用

时间:2015-04-07 11:26:28

标签: angularjs angularjs-directive

在Angular.js项目中,我使用ng-token-auth进行用户身份验证,我想整合Twitter Typeahead.js

我构建了一个指令,其中链接函数的内容是:

link: (scope, element, attrs) ->
        hs_list = new Bloodhound({
          datumTokenizer: Bloodhound.tokenizers.obj.whitespace('hs8'),
          queryTokenizer: Bloodhound.tokenizers.whitespace,
          remote: 'api/trainings/hs_list?q=%QUERY'
        })
        hs_list.initialize()
        element.typeahead(null, {
          name: 'hs-mapping-id',
          displayKey: 'hs8',
          source: hs_list.ttAdapter(),
          templates: {
            empty: [
              '<div class="empty-message">',
              'We cannot find this training',
              '</div>'
            ].join('\n'),
            suggestion: Handlebars.compile('<p class="clearfix"><strong>{{hs8}}</strong> &mdash; {{hs8_text}}<br /><span style="display:inline-block; height: 22px; overflow: hidden; white-space:nowrap; text-overflow:ellipsis; max-width: 400px;">{{hs6_text}}</span></p>')
          }
        })
        .bind( 'typeahead:opened', ->
          $(this).data('ttTypeahead').dropdown.$menu.addClass('overflow-hidden').perfectScrollbar()
        )
        .on 'keyup', ->
          $(this).data('ttTypeahead').dropdown.$menu.perfectScrollbar('update')

当我尝试使用它时,我得到了未经授权的访问重定向,因为Bloodhound请求中缺少auth标头。将auth标头添加到请求的方法是什么?

1 个答案:

答案 0 :(得分:0)

好的,我找到了答案!

ng-token-auth提供了一个帮助程序,它返回ajax settings object的标题:

  

$ auth.retrieveData( 'auth_headers')

因此,为了与Bloodhound一起使用,我们需要做的就是:

angular.module('app').directive 'trainingsList', ($auth) ->
    return {
      restrict: 'A'
      link: (scope, element, attrs) ->
        hs_list = new Bloodhound({
          datumTokenizer: Bloodhound.tokenizers.obj.whitespace('hs8'),
          queryTokenizer: Bloodhound.tokenizers.whitespace,
          remote:
            url: 'api/trainings/hs_list?q=%QUERY'
            ajax:
              headers: $auth.retrieveData('auth_headers')

        })
        hs_list.initialize()
        element.typeahead(null, {
          name: 'hs-mapping-id',
          displayKey: 'hs8',
          source: hs_list.ttAdapter(),
          templates: {
            empty: [
              '<div class="empty-message">',
              'We cannot find this training',
              '</div>'
            ].join('\n'),
            suggestion: Handlebars.compile('<p class="clearfix"><strong>{{hs8}}</strong> &mdash; {{hs8_text}}<br /><span style="display:inline-block; height: 22px; overflow: hidden; white-space:nowrap; text-overflow:ellipsis; max-width: 400px;">{{hs6_text}}</span></p>')
          }
        })
        .bind( 'typeahead:opened', ->
          $(this).data('ttTypeahead').dropdown.$menu.addClass('overflow-hidden').perfectScrollbar()
        )
        .on 'keyup', ->
          $(this).data('ttTypeahead').dropdown.$menu.perfectScrollbar('update')
    };