KnockoutJS - Attr Binding



This binding allows you to dynamically assign HTML elements attribute using ViewModel property. For example, you can set src attribute for an image, title attribute for HTML page, or a href for a link in the tag based on values in ViewModel.

Syntax

attr: <binding-object>

Parameter

  • JavaScript object should be passed as a parameter in which the property name refers to attribute name and values refer to the desired values to be passed to DOM element.

  • Multiple attributes can also be assigned at once. Suppose you want to assign a title and href a value, then binding will look like the following −

<a data-bind = "attr: { href: courseUrl, title: courseTitle}">

courseUrl and courseTitle variables will have the desired values in ViewModel.

  • If the ViewModel property is an observable value, then attribute is assigned depending on the new updated parameter value. If it is not an observable value, then attribute is assigned only once for the first time.

Example

Let us take a look at the following example which demonstrates the use of Attr binding.

<!DOCTYPE html>
   <head>
      <title>KnockoutJS attribute binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" 
         type = "text/javascript"></script>
   </head>
   
   <body>
      <a data-bind = "attr: { href: courseUrl}">
         Click here for free online tutorials and courses.
      </a>

      <script type = "text/javascript">
         function AppViewModel() {
            this.courseUrl = ("http://tutorialspoint.com/");
         };
         
         var vm = new AppViewModel();
         ko.applyBindings(vm);
      </script>
      
   </body>
</html>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above code in attr-bind.htm file.

  • Open this HTML file in a browser.

  • The courseUrl will assign the value to href attribute in HTML DOM element.

knockoutjs_declarative_bindings.htm
Advertisements