The ng:bind-attr
attribute specifies that a
databinding should be created between a particular
element attribute and a given expression. Unlike ng:bind
, the ng:bind-attr
contains one or
more JSON key value pairs; each pair specifies an attribute and the
expression to which it will be mapped.
Instead of writing ng:bind-attr
statements in your HTML, you can use double-curly markup to
specify an {{expression}} for the value of an attribute.
At compile time, the attribute is translated into an
<span ng:bind-attr="{attr:expression}"></span>
.
The following HTML snippet shows how to specify ng:bind-attr
:
<a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'>Google</a>
This is cumbersome, so as we mentioned using double-curly markup is a prefered way of creating this binding:
<a href="http://www.google.com/search?q={{query}}">Google</a>
During compilation, the template with attribute markup gets translated to the ng:bind-attr form mentioned above.
Note: You might want to consider using ng:href
instead of
href
if the binding is present in the main application template (index.html
) and you want to
make sure that a user is not capable of clicking on raw/uncompiled link.
<ANY ng:bind-attr="attribute_json"> ... </ANY>
attribute_json – {string} –
one or more JSON key-value pairs representing the attributes to replace with expressions. Each key matches an attribute which needs to be replaced. Each value is a text template of the attribute with the embedded {{expression}}s. Any number of key-value pairs can be specified.
Enter a search string in the Live Preview text box and then click "Google". The search executes instantly.
<script> function Ctrl() { this.query = 'AngularJS'; } </script> <div ng:controller="Ctrl"> Google for: <input type="text" ng:model="query"/> <a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'> Google </a> (ng:bind-attr) | <a href="http://www.google.com/search?q={{query}}">Google</a> (curly binding in attribute val) </div>
it('should check ng:bind-attr', function() { expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=AngularJS'); using('.doc-example-live').input('query').enter('google'); expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=google'); });