Vortilion
Vortilion

Reputation: 424

Angular: Controller-function in ng-if/ng-show doesn't get evaluated again when values changes

My Angular app has a simple controller and a template. The template has three text inputs. I want to show/hide an based on all three values being set (or not). Now what I experienced so far:

If I use a controller function to check the values, something like

ng-if="myCtrl.checkValues()"

and the function in the controller is defined as

vm.checkValues = checkValues;

function checkValues() {
     return vm.inputVal1 !== '' && vm.inputVal2 !== '' && vm.inputVal3 !== '';
}

Then I would expect it to be evaluated every time I update one or more of the values via entering something in the input fields. But it doesn't work. It only works if I don't use a function to check the values but use the functions line of code directly inside the ng-if. It seems that that the function is not being updated every time the values it checks are being changed, is that the case? Or am I missing something?

Upvotes: 1

Views: 199

Answers (2)

jomsk1e
jomsk1e

Reputation: 3625

If I get what you want correctly, you want to show/hide some element based on the 3 inputs and whenever the textboxes changes you want to update the hide/show element.

You can do that using ng-change and ng-show, here's an example, not tested but I hope it helps and gives you an idea:

<input type="text" ng-model="text1" ng-change="checkValues()/>
<input type="text" ng-model="text2" ng-change="checkValues()/>
<input type="text" ng-model="text3" ng-change="checkValues()"/>

<label ng-show="checkValues()">Test</label>

$scope.checkValues = function() {
    return $scope.text1 !== '' && $scope.text2 !== '' && $scope.text3 !== '';
}

Upvotes: 0

korteee
korteee

Reputation: 2692

Try return this expression:

$scope.checkValues = function() {
    return ($scope.input1 && $scope.input2 && $scope.input3);
  }

Here's a working plunker for you

Upvotes: 2

Related Questions