Vortilion
Vortilion

Reputation: 424

Angular ng-show depending on function

maybe its just a basic misunderstanding, but I have a small issue regarding Angular and ng-show.

I've got a simple form with three input fields. I want to show a div with an infotext, but only if all three input fields are set.

My controller (with controllerAs-Syntax, Alias is 'myControllerCtrl') looks like that:

var vm = this;

vm.annualConsumption = null;
vm.calorificVal = null;
vm.zNumber = null;
vm.checkIfAllValuesAreSet = checkIfAllValuesAreSet;


function checkIfAllValuesAreSet() {
    return vm.annualConsumption && vm.calorificVal && vm.zNumber;
}

So I put an

ng-show="myControllerCtrl.checkIfAllValuesAreSet()"

in my div. But it won't show the div if I set all input fields! If I put the condition from the function directly into the ng-show like

ng-show="vm.annualConsumption && vm.calorificVal && vm.zNumber"

it works. So my question is: Why can't I use the function as an expression for ng-show?

Upvotes: 1

Views: 1837

Answers (3)

laney
laney

Reputation: 354

Your ng-show="myControllerCtrl.checkIfAllValuesAreSet()" will only get run once when the controller/template loads. So if you change anything on your form, there is nothing to trigger the function again.

you could simply change your ng-show to be:

ng-show="vm.annualConsumption && vm.calorificVal && vm.zNumber"

which will update immediately if any of these change.

Upvotes: 1

illeb
illeb

Reputation: 2947

You are not using $scope. Attach the function to the scope of the controller, and you are good to go:

$scope.checkIfAllValuesAreSet = function() {
   return vm.annualConsumption && vm.calorificVal && vm.zNumber;
}

so in your HTML you'll able to do:

ng-show="checkIfAllValuesAreSet()"

remember, $scope are a very important concept of angularjs. Trying to avoid using it it's a bad idea. You can read the docs about $scope here.

Upvotes: 3

MSH
MSH

Reputation: 297

You can use function as an expression, but make sure that the function returns a boolean. Try this :

function checkIfAllValuesAreSet() {
if( vm.annualConsumption !=null && vm.calorificVal !=null && vm.zNumber !=null){
return true;
}

Upvotes: 0

Related Questions