Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why mixing interpolation and expressions is bad practice

Tags:

angularjs

From the Docs:

Embedding interpolation markup inside expressions

Note: AngularJS directive attributes take either expressions or interpolation markup with embedded expressions. It is considered bad practice to embed interpolation markup inside an expression:

— AngularJS Developer Guide - Interpolation

I am looking for a well written canonical answer to which I can point readers.

like image 945
georgeawg Avatar asked Jul 30 '18 10:07

georgeawg


People also ask

What we can t do with interpolation in Angular?

Interpolation makes use of the {{ }} double curly braces syntax to embed template expressions that will be converted by Angular into marked-up text in the view layer. This will throw an error, as declaring objects when using string interpolation isn't allowed.

Can we use interpolation inside interpolation in Angular?

In Angular, you can use interpolation syntax for data binding for an expression as {{ expression}} . You can use inline expression or member variable inside {{ }} interpolation operator. Sometimes, you would like to use different interpolation characters instead of {{ }} for data binding. For example [ expession ].

What is the use of text interpolation?

Interpolation refers to embedding expressions into marked up text. By default, interpolation uses the double curly braces {{ and }} as delimiters. Angular replaces currentCustomer with the string value of the corresponding component property.

What we can do with interpolation in Angular?

In AngularJS, Interpolation is a way to transfer the data from a TypeScript code to an HTML template (view), i.e. it is a method by which we can put an expression in between some text and get the value of that expression. Interpolation basically binds the text with the expression value.


2 Answers

From the Docs:

Why mixing interpolation and expressions is bad practice:

  • It increases the complexity of the markup

  • There is no guarantee that it works for every directive, because interpolation itself is a directive. If another directive accesses attribute data before interpolation has run, it will get the raw interpolation markup and not data.

  • It impacts performance, as interpolation adds another watcher to the scope.

AngularJS Developer Guide - Interpolation

like image 72
Daniel Avatar answered Oct 14 '22 02:10

Daniel


Directives which expect Boolean values won't work:

ERRONEOUS

<input type="checkbox" ng-hide ="{{x.thenumber === null}}" />

When the expression evaluates to the Boolean value false, interpolation will return the string "false". Strings that have length greater than zero are truthy. The ng-hide directive will always hide and never show the input element.

CORRECT

 <input type="checkbox" ng-hide="x.thenumber === null" />
like image 33
georgeawg Avatar answered Oct 14 '22 01:10

georgeawg