Vortilion Vortilion - 1 year ago 99
AngularJS Question

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


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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download