簡體   English   中英

在Angular工廠的函數中設置變量

[英]set a variable in a function from an Angular factory

我有一個Angular工廠,它會生成一個函數,該函數帶有為下拉列表選擇數組的變量。 看來我應該從控制器中的用戶選擇中設置該變量。 這兩個部分工作正常,但是我無法將變量添加到控制器的函數中。

該工廠有多個數組和一個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>

我正在苦苦掙扎的那個按鈕下拉指令的控制器。 當我對某些事情進行硬編碼時,雖然看起來不像“好的Angular代碼”,但是它可以工作。 當它變時,我遇到了各種各樣的問題。 我認為我應該使用$ scope,但這可能值得商question。 $ 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);

也許您需要調用函數?
$scope.ddMenuOptions = ddSelections.withLangChoice($scope.getCurrentLanguage($translate));
代替
$scope.ddMenuOptions = ddSelections.withLangChoice($scope.getCurrentLanguage);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM