在Angular工厂的函数中设置变量

时间:2014-09-03 00:33:13

标签: javascript angularjs angular-translate

我有一个Angular工厂,它生成一个带有变量的函数,该变量为下拉列表选择一个数组。我似乎应该从控制器中的用户选择中设置该变量。这2件工作,但我无法将变量放入控制器的函数中。

工厂有几个数组和一个switch()函数来选择一个。工厂返回一个功能。这是一些代码。 ddSelections是一个数组。

languageFactories.factory('changePostDdFactory', ['$translate', function (translate) {
    return {
        withLangChoice: function (langKey) {
            //variables containing arrays and a switch() to select based on langKey
            return ddSelections;
        }
    }
}]);

显示所选数组的按钮下拉列表的HTML是

<div id="postBox" class="floatingSection" data-ng-controller="postButtonController2">
  <button id="postButton" dropdown-menu="ddMenuOptions" dropdown-model="ddMenuSelected" class="btn-menu">{{ 'POST' | translate }}</button>
</div>

该按钮下拉指令的控制器是我在挣扎的地方。当我对其中的某些东西进行硬编码时,虽然它看起来并不像#34;良好的角度代码&#34;。当它的变量,我得到了各种各样的问题。我认为我应该使用$ scope,但也许这个问题值得商榷。 $ scope.getCurrentLanguage似乎是个问题。这是代码。

residenceApp.controller('postButtonController2', ['$translate', '$scope', 'changePostDdFactory',

function ($translate, $scope, ddSelections) {
    //hardcoded works at page load and shows my intention
    //$scope.getCurrentLanguage = 'en'; //creates Scope and Model for getCurrentLanguage & ddMenuOptions
    //$scope.ddMenuOptions = ddSelections.withLangChoice($scope.getCurrentLanguage); //shows correct array from factory
    //here's my latest of many attempts with a user selected variable that is accessed via the $translate directive
    //per Batarang there is no Scope and Model for getCurrentLanguage & ddMenuOptions
    $scope.getCurrentLanguage = function ($translate) {
        alert('here I am'); //does not fire
        $translate.use(); //getter per http://stackoverflow.com/questions/20444578/get-current-language-with-angular-translate
        return $translate.use(); //should return 'en' or 'es'
    };
    $scope.ddMenuOptions = ddSelections.withLangChoice($scope.getCurrentLanguage); //no dropdown, no array change
    //$scope.ddMenuOptions = ddSelections.withLangChoice(getCurrentLanguage); //page does not load
    $scope.ddMenuSelected = {};
    $scope.$watch('ddMenuSelected', function (newVal) {
        //if watch() triggers, do something
    }, true);

1 个答案:

答案 0 :(得分:1)

也许你需要打电话给你的功能?
$scope.ddMenuOptions = ddSelections.withLangChoice($scope.getCurrentLanguage($translate));
而不是 $scope.ddMenuOptions = ddSelections.withLangChoice($scope.getCurrentLanguage);