2015-04-07 52 views
0

在Angular.js項目中,我使用ng-token-auth進行用戶身份驗證,我想集成Twitter Typeahead.js使用ng-token-auth與typeahead/bloodhound

我已經建立了一個指令,其中的鏈接功能的內容是:

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

當我嘗試使用它,我得到的未經授權的訪問重定向,因爲AUTH頭文件是由尋血獵犬請求丟失。將auth頭添加到請求的方式是什麼?

回答

0

好的,我找到了答案!

NG-令牌身份驗證提供了一個助手,它返回頭爲ajax settings object

$ auth.retrieveData( 'auth_headers')

因此,爲了與警犬使用它,我們需要做的是:

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') 
    };