7

Say you have a template like

<a ng-show=function()>a link</a>

My question is: when is function run? How can I tell angular that it is time to re-run the function?

josinalvo
  • 1,366
  • 13
  • 26
  • 1
    ng-show takes a condition expression to run. The method is tied to the controller, and reacts to changes to that expression. So if you have `ng-show="checked"`, it's tied to $scope.checked in your controller. When that scope variable changes, the ng-show reacts – Sterling Archer Mar 24 '17 at 19:24

3 Answers3

3

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

$scope.show = false;

$scope.showSomething = function(myCondition){
    if(myCondition){
        myFunction();
        $scope.show = true;
    }
};
<div ng-show='show'></div>
samnu pel
  • 914
  • 5
  • 12
2

Any expression in ng-show is evaluated at every digest cycle, so the function is run on every digest cycle as well. Thus any change to the value returned by the function, will reflect in the view. If your function makes any changes to the application state that triggers a new digest cycle, you may run into an infinite digest loop (which isn't great).

So be careful about using functions in directives like ng-show. If the function is pure though (it doesn't have any side-effects), you should be safe using it.

Here's a plunker that shows the function being called on every digest. (Note: in the plunker example, clicking the button actually triggers two digest cycles, since the click event triggers one, and toggling the $scope variable triggers another.)

Nikolaj Dam Larsen
  • 5,455
  • 4
  • 32
  • 45
0

ng-show="booleanVar" takes a condition or a Boolean value . You can change the value of condition expression to hide and show values at run time .

But if you want some function to be called when ng-show is triggered then you can use $watch in your model .

<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!');
        }
    });
});

See details here

Community
  • 1
  • 1
Abdullah Al Noman
  • 2,817
  • 4
  • 20
  • 35