0

Im trying to learn the basics with AngularJS and trying to make a text visible when a number is big enough. It looks like the more() function is only called once, when the page is displayed first time. The lessThan3() function returns the correct value, but it doesnt work when trying ng-hide.

AngularJS

function ApplicationController($scope,$interval) {   
    $scope.number = 0;
    $interval(function() {
         $scope.number++;
    }, 1000);

    $scope.lessThan3 = function(){
        return ($scope.number < 3);
    }
}

Html

Number: {{ number }}
{{ lessThan3() }}
<p ng-hide="{{ lessThan3 }}">
    Less than 3
</p>

link to code: http://jsfiddle.net/bBaa2/71/

4 Answers 4

2

It's just

<p ng-show="more()">

for the jsfiddle, or

<p ng-hide="lessThan3()">

for the example here.

without {{}}

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

3 Comments

Ah! Thx. Thought I was supposed to use {{ }} when using variables and functions
This is for interpolation as a string. This is a bit special when you bind to attributes.
@joxxe don't forget to upvote and accept the answer if you like it :)
2

Change your HTML code to: <p ng-hide="number > 3">Less than 3</p> or to <p ng-hide="lessThan3()">Less than 3</p> if you prefer to call the method

You don't need the data binding syntax when using ng-hide/ng-show/ng-if/ and other similar directives.

function ApplicationController($scope,$interval) {
    
    $scope.number = 0;
  
    $scope.testTimer = function() {
        $interval(function() {
            $scope.number++;
        }, 1000);
    };
    $scope.lessThan3 = function(){
        return ($scope.number > 3);
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="ApplicationController">   
    <pre>Number: {{ number }}</pre>
    <button ng-click="testTimer()">Test Timer</button>
    <p ng-show="lessThan3()">
    More than 3
    </p>
    <p ng-hide="lessThan3()">
    Less than 3
    </p>
</div>

Comments

1

The syntax is incorrect:

<p ng-hide="lessThan3()">

But be aware that I also think your logic is incorrect if I can assume what you are trying to do. You want to hide the element when number is greater than 3. Or at least change the message.

Comments

0

You need to change your HTML:

<div ng-app ng-controller="ApplicationController">   
    <pre>Number: {{ number }}</pre>
    <button ng-click="testTimer()">Test Timer</button>

    <p ng-show="more()">
    More than 3
    </p>

    <p ng-hide="more()">
    Less than 3
    </p>
</div>

1 Comment

Not necessarily, if you check the funcion more is already looking for de number.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.