KnockoutJS Attr Bindings

In the previous articles we covered all most all of different types of appearance related bindings. We saw visible, text, html, css and style bindings. In this article we shall study the last type of appearance related bindings i.e. KnockoutJS attr bindings. Basically this type of binding sets the attribute value of any HTML DOM element. Typically you add url to href tag or image path to source tag using attr binding. The attr basically stands for attribute. Take a look at the following example to see knockoutJS attr bindings in action.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>


</head>
    
<body>
   <img data-bind="attr: { src: ImageAddress}" />
    

   <script>
      function ImageModel() {
this.ImageAddress= ko.observable('http://images.freeimages.com/images/previews/caf/communications-tower-1309311.jpg')
                                                                                                                             
      }
      var sm = new ImageModel();
      ko.applyBindings(sm);
   </script>
</body>
</html>

Download the code Try the code

Take a careful look at the above code. In the HTML view section, we have an image tag. Using the attr binding, the source attribute of the image tag has been assigned an ImageAddress parameter of the ImageModel. The ImageAddress parameter contains source of the image. In the JavaScript view model, we have an ImageModel which has an observable ImageAddress which contains some random image source,.

Parameter passed to the attribute binding is in the form of JavaScript object notation where parameter is the name of the attribute and the value is the value assigned to the parameter.

Modifying ‘Href’ of a Link

In the following example we shall explain how we can use parameter from the view model and assign its value to the href tag of a link. Take a look at this code:

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>


</head>
    
<body>
   <a data-bind="attr: { href: LinkAddress}">
       
       link to google
    </a>
    

   <script>
      function ImageModel() {
this.LinkAddress= ko.observable('www.google.com');
                                                                                                                             
      }
      var sm = new ImageModel();
      ko.applyBindings(sm);
   </script>
</body>
</html>

Download the code Try the code

In the above code, in the html view, we have an anchor tag. The attribute binding binds he href attribute of the anchor tag to the LinkAddress parameter of the ImageModel. Now if you open the above page in browser, you shall see a link that points towards google.com.

In the next article, we shall start studying control flow binding. Happy Coding!

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .