Tips for Using Angular Directives

My directive is data-driven and generates radio buttons that have been styled to look like buttons.

While everything is functioning correctly, I would like to be able to specify an image URL for each item and dynamically display the corresponding image in ng-repeat (representing the button). Currently, the image URL is set in the CSS, limiting me to only one type of button. I need a more dynamic solution than that.

Any advice or pointers on how to achieve this would be greatly appreciated.

Thank you.


CSS

        #buttonBox label {
            display: inline-block;
            cursor: pointer;
            position: relative;
            padding-left: 13px;
            margin-right: 46px;
            font-size: 13px;
        }

        #buttonBox label:before {
            content: "";
            width: 60px;
            height: 60px;
            border-radius: 8px;
            margin-right: 10px;
            display: inline-block;
            background-image: url('app/images/blue.png');
        }

        #buttonBox input[type=radio] {
            display: none;
        }

        #buttonBox input[type=radio]:checked + label:before {
            content: "";
            background-image: url('app/images/yellow.png');
        }

HTML

<da-buttons model="phone" items='phones' checked-index="0"></da-buttons>

Controller (these are the items)

$scope.phones = [ {
    text: "Android",
    group: "phoneGroup",
    value: 9
}, {
    text: "iOS",
    group: "phoneGroup",
    value: 10
}, {
    text: "Blackberry",
    group: "phoneGroup",
    value: 11
}];

Directive

var directives = angular.module('myApp.directives');

directives.directive('daButtons', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            model: '=',
            items: '=',
            checkedIndex: '@'
        },
        templateUrl: 'template/button-group.html',
        link: function(scope) {
            scope.onItemChange = function(item) {
                scope.model = item;
            };
        }
    };
});

Template: button-group.html

<div ng-repeat='item in items' id="buttonBox">
    <input
       type="radio"
       name="{{item.group}}"
       value="{{item.value}}"
       ng-model="model.value"
       ng-checked="$index==checkedIndex">
    <label ng-click="onItemChange(item)">{{item.text}}</label>
</div>

Answer №1

Currently, the image URL is specified in the CSS, limiting me to only using one type of button design.

However, there is a way to work around this limitation. By creating different classes for each image in your CSS file, you can have multiple options for button designs:

.image-1 {
    background-image: url('path/to/image_1.png');
}

.image-2 {
    background-image: url('path/to/image_2.png');
}

.image-3 {
    background-image: url('path/to/image_3.png');
}

Then, with the use of the ng-class directive in AngularJS, you can dynamically select which image to display based on certain conditions. Here's an example (excluding other template details for simplicity):

<input ng-class="{determineClass(): true}[0]">

The determineClass() function within your directive's scope will determine which specific image-* class should be applied based on your requirements.

Answer №2

An inline approach would be my choice as it avoids the need for CSS modifications. Additionally, if the phones JSON data is dynamic, then this method becomes even more advantageous as no changes are required to ensure that the directive correctly displays images.

$scope.phones = [ {
        text: "Android",
        group: "phoneGroup",
        value: 9,
        image: 'img1'
    }, {
        text: "iOS",
        group: "phoneGroup",
        value: 10,
        image: 'img2'
    }, {
        text: "Blackberry",
        group: "phoneGroup",
        value: 11,
        image: 'img3'
    }];

Directive:

<div ng-repeat='item in items' id="buttonBox">
    <input
       type="radio"
       name="{{item.group}}"
       value="{{item.value}}"
       ng-model="model.value"
       ng-checked="$index==checkedIndex"
       class="set whatever class you need"
       style="background-image:url({{item.image}})">
    <label ng-click="onItemChange(item)">{{item.text}}</label>
</div>

Answer №3

To create a unique and customizable look, utilizing CSS classes is the most versatile and subtle method. Within the controller, set the className property as follows:

$scope.phones = [{
    text: "Android",
    group: "phoneGroup",
    value: 9
}, {
    text: "iOS",
    group: "phoneGroup",
    value: 10,
    className: 'fade-button' // <--- any custom class name
}, {
    text: "Blackberry",
    group: "phoneGroup",
    value: 11,
    className: 'circle-button' // <---
}];

In the template section:

<div ng-repeat='item in items' id="buttonBox" class="{{item.className}}">
    ...
</div>

You can then define the necessary CSS rules to style your newly created checkbox:

#buttonBox.fade-button label:before {
    background-image: url(some-image.png);
    background-color: red;
}
#buttonBox.fade-button input[type=radio]:checked + label:before {
    background-image: url(...);
}

Check out the demo here: http://plnkr.co/edit/YnIbCbW9jnzsZSMX8abL?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues have been encountered with the AngularJS Modal functionality when trying to populate data within an ng

Attempting to utilize a bootstrap modal for updating data in a list, the initial modal being used is to add a new item to said list. Successfully created the modal, triggered the ajax call, and returned the data to the main controller via the promise belo ...

Firefox fails to apply styles to elements that are empty

Below is a snippet of code for a table with editable content: table { border-collapse: collapse; } th, td { border: 1px solid gray; padding: 3px 6px; } [contenteditable]:empty:not(:focus)::before { content: attr(data-placeholder); color: gr ...

What is the best way to store JSON data in the state of a ReactJS application?

I need assistance with a data format related issue. The current format of the data is being set by someone else in the backend of the application. When the data is empty, it looks like this: "opening_time":{"Mon":[["0"],["0"]], "Tue":[["0"],["0"]], "Wed" ...

Guide to adding a personalized HTTP header to ajax request using JavaScript or jQuery

Is there a way to create a custom HTTP header using JavaScript or jQuery? I've tried the code below but it's giving me an error of 405 Method not Allowed. I'm using the POST method, but in the request it shows as OPTION. The status code is ...

Is it necessary to bump the major version if I make updates to a react module that does not affect existing code functionality, but may cause Jest snapshot tests to break?

Imagine I am developing a module for a react component and currently working on a PR to introduce a new feature. Along with this new feature, I have also made changes to the component by refactoring it to eliminate certain internal parts that were previou ...

Ways to test and simulate a $timeout function during unit testing

Is there a way to simulate the timeout function being called in this code snippet? $scope.submitRequest = function () { var formData = getData(); $scope.form = JSON.parse(formData); $timeout(function () { $('#submitForm'). ...

I'm in the process of constructing a create-next-app and I need to retrieve data from a web API. However, I'm unsure of the best place to securely store the API key

I am working on building a create-next-app that will retrieve data from the News Catcher API and display it within my application. I have obtained an API key to access the News Catcher API. However, I am unsure of where to securely store the API key and h ...

Steps for importing an image into a phpMyAdmin database and associating it with a particular username

My goal is to upload images to a phpmyadmin database and associate them with specific usernames. I then want to retrieve these images and display them on an HTML page using jQuery, AJAX, PHP, and JavaScript. As a beginner, I am looking for the simplest way ...

What could be causing a specific CSS class to not take effect?

Recently, I embarked on a journey to learn Django framework with Python. My main source of knowledge is a course I found on YouTube. However, I encountered an issue where the CSS and JS features were not applying to my page as demonstrated in the course. ...

JavaScript is unresponsive and fails to display

I attempted to incorporate my initial Javascript snippet into a browser to observe its functionality. However, upon adding these lines directly into the body of my HTML code (even though I am aware that there are more efficient methods), no visible changes ...

Unable to combine two items within the same row in the cell

My current structure looks like this: <td class="sorting_1" tabindex="0"> <div class="form-check" data-user-id="1"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" value=""> ...

A dynamic JavaScript object that functions similarly to a multidimensional associative array in PHP

How can you efficiently update or add properties to an object in JavaScript? Unlike PHP's associative array, achieving this dynamically in JavaScript can be a bit tricky. For example: $test = []; foreach ($data as $key => $value) { ... $te ...

JavaScript's multiple inheritance concept

In the realm of JavaScript, there exists a class that seeks to 'inherit' various objects and their methods. var A = function (a,c){}; var N = { properties1: function(){}; }; var M1 = { properties2: function(){}; }; var M2 = { ...

Is there a way in AngularJS to trigger an event at a designated time?

I recently developed a webpage using AngularJS. I am looking to trigger certain actions on my webpage within a specified timeframe. For instance, If it is 2016-01-07 11:00:00, I want ng-show to execute some action. I am utilizing the Angular-timer for ...

Implementing a function trigger on button click using jQuery

I recently created a jQuery code snippet: <span id="counter-up" class="timer"> </span> <div class="buttons"> <button id="trigger">Find out!</button> </div> </div> <div class="container"> </div> & ...

Relocating to reveal or conceal item

I am currently working with jQuery and trying to achieve a specific functionality. My goal is to hide and unhide an element, while also focusing on the exposed area once it becomes visible. I have a link #welcomeselect that, when clicked, should reveal t ...

Using React js to retrieve data from multidimensional arrays

I am currently working on interacting with a json api. Initially, I was able to access the api and display the first array using the map method. However, I am facing difficulty in accessing anything beyond that initial array. { "client_id": 1, "client_nam ...

Step-by-step guide on interacting with a JavaScript menu: Click to open the menu and close it by moving

My menu JavaScript function now opens with a click and closes with a click. I want it to open with a click and close when the mouse leaves the button. $("#theme_select").click(function() { if (theme_list_open == true) { $(".center ul li ul").h ...

capturing webpage content with javascript for use in a screenshot

Is there a way to capture a screenshot of a webpage using JavaScript and utilize the canvas tag for this purpose? I attempted to use the html2canvas plugin in the past, but found it lacking in power. I would like to achieve this without relying on extern ...

Shrink the size of the fixed navigation menu

I am experiencing a significant issue with a fixed menu when the browser is resized, as the list items are overlapping and extending beyond their defined section. It's quite frustrating :(. I have been considering two possible solutions: 1: Set a fixe ...