2

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?

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
PHPLover
  • 1
  • 51
  • 158
  • 311

1 Answers1

3

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 {{}}

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Then how does it working in first example? It shouldn't have been working in first example as well. – PHPLover May 16 '16 at 13:55
  • I dont think the first one works either. Tried it out and both seems to be not working.here is a jsfiddle of it not working https://jsfiddle.net/U3pVM/24828/ @PHPLover. Works if I make the changes suggest above. You might want to recheck your output again. – Imprfectluck May 16 '16 at 13:58
  • 1
    @Imprfectluck see here is the example 1st one worked but second one doesn't [plunkr here](https://plnkr.co/edit/a32clodMJcwFRNbzEjRZ?p=preview) – Pankaj Parkar May 16 '16 at 14:00
  • @Imprfectluck check console `window.angular.$$csp is not a function` – Pankaj Parkar May 16 '16 at 14:03
  • @PHPLover look at the updated in detail answer..that will answer your all question related curiosity. Thanks :) – Pankaj Parkar May 16 '16 at 14:11