Call a function when ng-show is triggered?

前端 未结 3 1633
耶瑟儿~
耶瑟儿~ 2020-12-15 15:38

I want to show a lightbox with the content being revealed by ng-show, but I don\'t know how to trigger the lightbox JS. I\'m looking for something like

ng-on         


        
相关标签:
3条回答
  • 2020-12-15 15:48

    Well, ng-show takes a Boolean value, so your best option for using it is to call your showLightbox function somewhere in the logic that sets ng-show.

    $scope.reasonToShow = false;
    
    $scope.showSomething = function(myCondition){
        if(myCondition){
            showLightbox();
            $scope.reasonToShow = true;
        }
    };
    
    <div ng-show='reasonToShow'></div>
    

    You could do something similar with a $watch if you needed to.

    0 讨论(0)
  • 2020-12-15 16:03

    what about a simpler approach?

    let's say you have an element like this:

    <div ng-show="someBooleanValue"></div>
    

    If you use an AND operator after displayMyDiv and put a callback there, the callback would be only executed if the first value is TRUE ( that's how the logical AND operator works ). So this is what I tried with angular 1.15.10 and it works:

    $scope.showLightbox = function() {
      // your logic goes here
      return true;
    }
    
    <div ng-show="someBooleanValue && showLightbox()"></div>
    

    If and only if someBooleanValue is true, then $scope.showLightbox() will be evaluated also. So you will have to make $scope.showLightbox() to return TRUE, else your div won't be visible.

    This way is not only simpler, it also handles the observer implementation to angular ( less code to maintain ), and the callback return will be evaluated only if someBooleanValue changes to TRUE.

    0 讨论(0)
  • 2020-12-15 16:10

    I think, it would be better to $watch your model, on which ng-show is bound.

    Here is example:

    <div ng-app="myApp" ng-controller="myCtrl" ng-init="isDisplayed = true">
        <div ng-show="isDisplayed">something</div>
        <button ng-click="isDisplayed = !isDisplayed">Toggle</button>
    </div>
    
    var myApp = angular.module('myApp', [])
    .controller('myCtrl', function($scope, $log) {
        $scope.$watch('isDisplayed', function(newValue, oldValue) {
            if (newValue !== oldValue) {
                $log.log('Changed!');
            }
        });
    });
    

    and fiddle

    0 讨论(0)
提交回复
热议问题