Directive scope variable not working with ng-show

拟墨画扇 提交于 2019-12-12 05:27:44

问题


I have a "home" controller that uses a directive. I want to be able to show/hide a button in the directive template depending on the value of a variable in the controller.

This is what my directive looks like:

angular.module("goleadoresApp").directive("golNavbar", [golNavbar]);
function golNavbar() {
    return {
        restrict: "EA",
        templateUrl: "views/templates/golNavbar.html",
        scope: {
            pageTitle: "@",
            showLockIcon: "@"
        }
    };
}

And my template:

<div class="bar bar-header bar-balanced">
     <h1 class="title">
         <i class="gol-logo-icon icon ion-ios-football"></i>
        <span ng-bind="pageTitle"></span>
     </h1>
     <!--For testing purposes: This variable renders as false, however, ng-show in line below doesn't work-->       
     {{showLockIcon}} 
     <!--ng-show won't work. Element would still be visible even if showLockIcon is false-->
     <a class="button icon ion-locked pull-right second-right-button" 
        ng-show="showLockIcon"></a>
     <a class="button icon ion-help-circled" href="#/help"></a>
</div>

From my view, I'll use the template and pass it a controller variable (canPredictionsBePosted) that holds a value of true or false, and for which I expect that, if true, button will show in the template:

<gol-navbar page-title="{{matchWeek}}"
            show-lock-icon="{{canPredictionsBePosted}}"">
</gol-navbar>

When running this code, I can actually see that the value passed to showLockIcon template variable is correct, but the element in the directive template, which has the ng-show, won't work. That means that when I pass it a value of false, the button is still visible.

Any ideas?

Furthermore, if I change the value of the canPredictionsBePosted variable in my home controller, the value of showLockIcon in the template doesn't get updated. How could I get this to work?

Thanks in advance, I'm new to directives, so all help is appreciated.


回答1:


You need to make two changes.

1) Use = for showLockIcon like below:

    scope: {
        pageTitle: "@",
        showLockIcon: "="
    }

2) Remove the curly braces around canPredictionsBePosted in show-lock-icon="{{canPredictionsBePosted}}"

<gol-navbar page-title="{{matchWeek}}"
            show-lock-icon="canPredictionsBePosted">
</gol-navbar>


来源:https://stackoverflow.com/questions/45217353/directive-scope-variable-not-working-with-ng-show

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!