Angular when to use curly braces

In angular, sometimes I saw curly braces, but several times not.i searched a lot, but I could not find the right question

with brace

ng-src="{{imageSrc}} 

without braces

 ng-hide="imageSrc" 

that I ask why we cannot write ng-hide as

 ng-hide="{{imageSrc}} // doesn't work anyway 

why are there 2 different syntax for src and hide ?

+6
source share
3 answers

It just depends on how your directive is specified.

If the directive has the following declaration:

 scope:{ ngHide: '=' } 

then you do not need to use a double mustache because the directive expects an object

If the directive is declared as follows:

 scope:{ ngMin:'@' } 

then he expects value. If your value comes from a javascript variable, you need to use curly braces to interpolate the string contained in your variable.

EDIT:

It has been a long time since I read the angular source code.

I did not find the source code to prove my point:

ngController , which expects the string to be declared as follows

 var ngControllerDirective = [function() { return { restrict: 'A', scope: true, controller: '@', priority: 500 }; }]; 

https://github.com/angular/angular.js/blob/master/src/ng/directive/ngController.js#L3

ngMaxLength

 var maxlengthDirective = function() { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var maxlength = -1; attr.$observe('maxlength', function(value) { var intVal = toInt(value); maxlength = isNaN(intVal) ? -1 : intVal; ctrl.$validate(); }); ctrl.$validators.maxlength = function(modelValue, viewValue) { return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength); }; } }; }; 

https://github.com/angular/angular.js/blob/master/src/ng/directive/validators.js#L186

+6
source

So these are different things. When you use this:

 <span data-ng-bind="test"> 

This means that angular will go into scope and get the value from there with the test as a key. So the value will be $ scope.test. But the attribute value will be "checked"

When you use

 ng-src="{{imageSrc}} 

then the value will be evaluated and placed in the attribute. So the value will be $ scope.imageSrc and the attribute value will be $ scope.imageSrc.

But. Not all tags can wait for an evaluation. They believe the value {{}} is correct and will not be changed. This leads to bad queries. To fix this problem, ng-src was created.

+5
source

You cannot write, because both have different meanings, see this link, All about expressions and template arguments.

https://docs.angularjs.org/api/ng/directive/ngSrc

 ng-src=template 

You can find it in the argument

https://docs.angularjs.org/api/ng/directive/ngHide

 ng-hide=expression 

You can also find it in the argument

+4
source

All Articles