When to use double braces {{}} in angularJS

后端 未结 2 1067
别跟我提以往
别跟我提以往 2020-12-05 14:40

Taken from the Angular documentation:

Angular Expressions
Angular expressions are JavaScript-like code snippets that are mainly placed in inte

2条回答
  •  醉梦人生
    2020-12-05 15:34

    It depends on the directive attribute in question and the type of binding it uses. Further more it depends on what you intend in the given situation.

    From your example:

    ng-repeat="appModule in applicationModules"
    

    No need for the braces as this expression is evaluated by angular inside the ng-repeat directive.


    id="{{appModule.Name}}"
    

    Here we need braces as we want the id to be equal to the value of the expression.


    ng-class="{ 'selected' :  selectedAppModule == '{{appModule.Name}}' }"
    

    I'm pretty sure this can be written as:

    ng-class="{ 'selected' :  selectedAppModule == appModule.Name }"
    

    And you get the same behaviour.


    ng-click="menuClicked(appModule.Name)"
    

    In this example we need the ng-click to be bound to the method named menuClicked.


    Generally we use {{}} when we want to evaluate the expression and when dealing with attributes we don't always need to use {{}} as they are in many cases evaluated behind the scenes.

    Simple Tip A rule of thumb for when {{}} is needed is by thinking of it as a wrapper for a .ToString()-method. Does converting the expression to a string make sense, then so does using {{}}. (Any counter examples are very welcome)

提交回复
热议问题