Wednesday, March 20, 2013

TIP: Setting title attributes of option tags of select directive of angularjs

The Desktop App for YouTube™ is implemented using Angularjs. In it I use the select directive like this:

<select id="video-titles" multiple="" ng-model="selectedYouTubeVideoArray" ng-options="youTubeVideo.title for youTubeVideo in youTubeVideos">
</select>

The select directive generates the option tags based on the model. However this means that I cannot set the title attributes of option in the markup. I achieved in the JavaScript like this:

// populate the $scope.youTubeVideos array
$scope.youTubeVideos = [];
angular.forEach(data.data.items, function(item) {
    $scope.youTubeVideos.push(new YouTubeVideo(item));
});
// then loop through the options and set title
setTimeout(function()  {
    var options = document.querySelectorAll("#video-titles option");
    if (options) {
        for (var i = 0; i < options.length; i++) {
            options[i].title = options[i].textContent;
        }
    }
}, 0);

Note however that I had to use the setTimeout(..., 0) to set the title so that Angularjs actually gets the chance to create child option tags.

Hope this helps you!

2 comments:

Vick Sa said...

HTML Attributes are property of the elements which may have values and these attribute values are always enclosed in quotes. It’s providing to the browser with some additional information about an elements how the elements should appear or behave. HTML elements can contain one or more attributes, attribute names and attribute values are case-insensitive and separated by an equals (=) sign.

[HTML Attributes](http://www.willvick.com/HTML/HTMLAttribute.aspx)

[HTML Attributes Examples](http://www.willvick.com/HTML/HTMLExampleAttribute.aspx)

[Youtube - HTML Tutorial - Attributes](http://www.youtube.com/watch?v=ucOXvaCEZgg)

Vick Sa said...

HTML Attributes are property of the elements which may have values and these attribute values are always enclosed in quotes. It’s providing to the browser with some additional information about an elements how the elements should appear or behave. HTML elements can contain one or more attributes, attribute names and attribute values are case-insensitive and separated by an equals (=) sign.

[HTML Attributes](http://www.willvick.com/HTML/HTMLAttribute.aspx)

[HTML Attributes Examples](http://www.willvick.com/HTML/HTMLExampleAttribute.aspx)

[Youtube - HTML Tutorial - Attributes](http://www.youtube.com/watch?v=ucOXvaCEZgg)