1

I've got this code:

<html>
<head>
</head>

<div ng-app="" ng-controller="Test">
<input type="text" ng-model="inputty">
<p>{{output}}</p>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>    
<script>
  function Test($scope){
    if($scope.inputty=="Hello") {
      $scope.output="OK!";
    } else {
      $scope.output="NOT OK!";
    }
  }
</script>
</html>

But it's not working, the NOT OK! displays. But it's like the if statement can't read from inputty. So it should state OK! when I type Hello in the input box.

1
  • $scope.output = function(){ return $scope.inputty=="Hello" ?"OK!" : "NOT OK!"; } and do <p>{{output()}}</p> Commented Sep 10, 2014 at 19:20

2 Answers 2

3

You need to add in a watch in your controlller in order to check the value of inputty and inside the watch function have the if loop so that you can change the output scope variable

Code:

function Test($scope) {
    $scope.inputty = '';
    $scope.$watch('inputty', function () {
        if ($scope.inputty == "Hello") {
            $scope.output = "OK!";
        } else {
            $scope.output = "NOT OK!";
        }
    });
}

Working Fiddle - $watch

Reference for $watch

Alternatively,

You can do it alone in HTML markup using ng-switch

HTML markup

<div ng-app ng-controller="Test">
    <input type="text" ng-model="inputty" />
    <div ng-switch="inputty">
        <p ng-switch-when="Hello">OK!</p>
        <p ng-switch-default>NOT OK!</p>
    </div>
</div>

Working Fiddle - ng-switch

Reference for ng-switch

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry I'm quite new angular, is there an easier way to do this? I would have thought using a loop wouldn't be needed.
Its not a loop its a watcher function which will check the value of inputty ( an event in controller) so that controller then can check the value and set the output variable accordingly, otherwise an event needs to be thr in order to let the controller do the comparision
WHy watch/ng-switch etc.. it should be as simple as return $scope.inputty=="Hello" ?"OK!" : "NOT OK!";
In best practice, you should avoid polluting controller's with $watch. Once you have everything refactored into their file instead of all inline on the one html page, everything starts to get easier.
0

If you only change your inputty through textbox, the easiest way is to use ngChange.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.