我正在尝试在AngularJS组件中使用$ translate.proposedLanguage(),这允许我初始化和配置intl-tel-input插件:
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 :(得分: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中启用设置,无论如何这样做都会更好,因为它可以缩小文件。