2017-05-22 66 views
0

我試圖使用$ translate.proposedLanguage()在AngularJS組件,它可以讓我初始化和配置INTL-TEL-輸入插件:

function customTel() { 
return { 
    restrict: 'A', // restrict as Attr 
    require: 'ngModel', // require ngModel from html 
    scope: {}, 
    link: function($scope, $elem, $attrs, $ctrl) { 

     var ngModelCtrl = $ctrl; // access to ngModel with $ctrl 

     var lenguaje = $translate.proposedLanguage() || $translate.use(); 

     if (lenguaje === "es") { 
      lenguaje = "ES"; 
     } else if (lenguaje === "en") { 
      lenguaje = "GB"; 
     } else if (lenguaje === "pt-pt") { 
      lenguaje = "PT" 
     } 

     $elem.intlTelInput({ 
      initialCountry: lenguaje, 
      preferredCountries: ["ES", "GB", "PT", "US"], 
      nationalMode: true, 

      utilsScript: "../../webclientes/bower_components/intl-tel-input/build/js/utils.js" 
     }); 

    } 
} 
} 

    angular 
     .module('webclientesApp') 
     .directive('customTel', customTel); 

的問題是,$語言是不確定的,即使我把它注射到控制器:

(function() { 
    'use strict'; 

    angular 
     .module('webclientesApp') 
     .controller('ContactaController', ContactaController); 

    ContactaController.$inject = ['$scope', 'Principal', 'ContactaServiceRest', '$state', '$translate']; 

    function ContactaController ($scope, Principal, ContactaServiceRest, $state, $translate) { 

... 

我試圖在鏈接參數注入,或在下面的.directive,但迄今沒有奏效。

如何通過組件訪問$ translate?謝謝!

+0

將函數customTel()'改爲'函數customTel($ translate)'。查看[這個問題](http://stackoverflow.com/questions/15569168/injecting-service-to-directive)瞭解更多信息 – George

+0

感謝您的幫助,@george。剛試過,得到了這個錯誤:錯誤:[$ injector:strictdi] customTel沒有使用明確的註解,並且不能在嚴格模式下調用。任何想法爲什麼發生這種情況?我正在檢查你提供的答案,但是沒有給出關於這個錯誤的任何信息:( – wickedchild

回答

2

如果你改變你的代碼,這樣它應該工作:

angular 
.module('webclientesApp') 
.directive('customTel', customTel); 

customTel.$inject = ['$translate']; 

function customTel($translate) { 
    return { 
     restrict: 'A', // restrict as Attr 
     require: 'ngModel', // require ngModel from html 
     scope: {}, 
     link: function ($scope, $elem, $attrs, $ctrl) { 

      var ngModelCtrl = $ctrl; // access to ngModel with $ctrl 

      var lenguaje = $translate.proposedLanguage() || $translate.use(); 

      if (lenguaje === "es") { 
       lenguaje = "ES"; 
      } else if (lenguaje === "en") { 
       lenguaje = "GB"; 
      } else if (lenguaje === "pt-pt") { 
       lenguaje = "PT" 
      } 

      $elem.intlTelInput({ 
       initialCountry: lenguaje, 
       preferredCountries: ["ES", "GB", "PT", "US"], 
       nationalMode: true, 

       utilsScript: "../../webclientes/bower_components/intl-tel-input/build/js/utils.js" 
      }); 

     } 
    } 
} 

你需要注入你的依賴在指導作用,而不是在鏈接功能。此外,您收到注入錯誤的原因是由於您可以在角度see the documentation中啓用的設置,因此以這種方式更好,因爲它允許文件被縮小。

+0

Spot on!:)我在AngularJS世界中很新,我仍然很難理解它是如何工作的。非常感謝喬治:))) – wickedchild

+1

@wickedchild我們都開始在某個地方,我建議給[約翰帕帕的風格指南](https://github.com/johnpapa/angular-styleguide/blob/master/a1/README。 MD)一讀。 – George

相關問題