当在控制器级别的范围内设置变量时,如何使变量可用?

时间:2015-04-28 16:53:15

标签: angularjs

控制器低于指令。我正在尝试获取适当翻译的语言代码。这就是控制器级别的内容。

PaymentPage.get($ scope.pageTag)

        .success(function(response) {

            $scope.product = response;
            console.log($scope.product);

            // get the language of the product assuming its a valid language code
            var lang_string = $scope.product.language;

            //take the first two letters of the language and honoring the caveat of en-f for example
            var lang = lang_string.substring(0,2);

            // Translate the page guideline
            $translate.use(lang);

            loadCampaigns($scope.product.language);
            initialiseBraintree(braintreeApiKey);
        });

但是,控制器上方有一个popover指令。该指令看起来像这样。我以为我能够使用$scope.product.language检索语言代码,但我意识到这是在控制器中发生的,因此指令无法访问它。

.directive('popover', function($translate) {
        // language scope is being set afterwards, must be set before to make use of $translate.use

    //$translate.use('de');

    var mouseOffset = 10;
    return {
        link: function (scope, element, attrs) {

            // Returns a promise and must be handled with a .then

            $translate('HOVER_MESSAGE').then(function (popover) {

                console.log(popover);

                var popoverElement = angular.element('<div class="myPopover hide">' + popover + '</div>');

                element.after(popoverElement);

                scope.popoverElement = popoverElement;

            });

此外,该指令在控制器之前加载,因此在隐藏跨度中隐藏语言代码等其他黑客也会失败。

1 个答案:

答案 0 :(得分:1)

我现在无法尝试这一点,但您应该能够使用该模型来弥合范围和时间差距。如果将指令的属性绑定到product.language(来自控制器中的$scope.product.language),那么当控制器提供语言代码时它将重新呈现指令,并且它将在通过的attrs中可用指令link()

类似于HTML中的内容:

<button id="buyNowButton" type="submit" popover language="{{product.language}}">

在你的指令中:

return {
    link: function (scope, element, attrs) {
        var lang = attrs.language;
        ...