PHPLover
PHPLover

Reputation: 12957

String expression does not work with ng-bind directive whereas number expression does?

See below examples of AngularJS code:

Ex. 1:

<!DOCTYPE html>
<html>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>
        <div ng-app="" ng-init="quantity=1;cost=5">
            <p>Total in dollar: <span ng-bind="{{quantity * cost}}"></span></p>
        </div>
    </body>
</html>

Output of above program is: Total in dollar: 5

Ex. 2:

<!DOCTYPE html>
<html>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>
        <div ng-app="" ng-init="firstName='John';lastName='Doe'">
            <p>The full name is: <span ng-bind="{{firstName + ' ' + lastName}}"></span></p>
        </div>
    </body>
</html>

Output of above program is: The full name is:

Why the full name is not appearing in output of second program?

Upvotes: 2

Views: 1247

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

You should not use {{}} interpolation again in ng-bind directive

ng-bind="(quantity * cost)"

ng-bind="firstName + ' ' + lastName"

The reason 1st got worked is the the evaluated output of quantity * cost which is 5 tries to evaluated with scope which is 5, but when we pass firstName + ' ' + lastName, it throws the error in console which is $parser: Syntax error.

The reason behind error is, 1st it tries to evaluate {{}} interpolated value which output would be John Doe & thereafter it evaluate result and try to search in the scope again, where it is trying to search John Doe(in correct variable name having space in it) in scope. Since it throws an error.


You can try one thing, change your ng-bind to have it without space like ng-bind="{{firstName + lastName}}"(just concatenation of two variables). You can see error will not happen in console. But still you will not see any output on screen as JohnDoe variable isn't available in scope. So just try to add some value for JohnDoe on ng-init(just for testing) like ng-init="JohnDoe='Mytest'", it will display output.

Preferred way to use ng-bind is without {{}}

Upvotes: 3

Related Questions