Transforming ng-if state and img src dynamically in an Angular (1) directive

I've recently been exploring different ways to optimize my code, specifically by utilizing a directive instead of the standard img tags. I'm aiming to dynamically modify the ng-if state and the src based on the input value in the directive.

Currently, the code resembles the following:

directive-

'use strict';
angular.module('myApp').directive('listImg', function() {
return {
    retrict: 'E',
    templateUrl: 'templates/list-img.html',
    scope: {
        show: '@',
    },
    link: function($scope) {

        $scope.iconImg;

        if ($scope.show == "opt1") {
            $scope.iconImg = "images/img1.png";
        } else if ($scope.show == "opt2") {
            $scope.iconImg = "images/img2.png";
        } else if ($scope.show == "opt3") {
            $scope.iconImg = "images/img3.png";
        } else if ($scope.show == "opt4") {
            $scope.iconImg = "images/img4.png";
        }

    }
}
});

template-

<img ng-if="show" ng-src="{{iconImg}}" class="list-image">

and then-

<list-img show="{{item.opt1 ? 'opt1' : ''}}"></list-img>

I haven't been able to successfully implement this and it doesn't seem like the most efficient method... If anyone has any suggestions on how to enhance/revise it, I would greatly appreciate it!

Thank you

Answer №1

Implement ng-if correctly by checking the condition's identity, such as

<img ng-if="item.opt1!=''" src="{{item.opt1}}" />
and
<img ng-if="item.opt1==''" src="noimg.jpg" />

Give it a shot!

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

Unusual occurrences of backslashes in arrays when using JSON.stringify

While experimenting with JavaScript, I observed an unusual behavior when inserting a backslash \ into a string within an array and using JSON.stringify() to print it. Normally, the backslash is used for escaping special characters, but what if we actu ...

Is it possible for a lambda in TypeScript to have access to the class scope but return undefined

In my TypeScript code, I have a class used as a Pipe in Angular 2 to render markdown. It compiles successfully but encounters a runtime exception on a specific line: var Remarkable = require('remarkable'); @Pipe({ name: 'markdown' ...

Leverage the basename feature in React Router when rendering on the server side

My website is being hosted from the directory /clientpanel on my server, making the URL http://xxx.yy/clientpanel. The client-side code looks like this: const history = useRouterHistory(createHistory)({ basename: "/clientpanel" }); render( <Ro ...

Issue with Material-UI DataGrid Component: Unable to access property 'length' as it is undefined

I need to display my JavaScript Object Data in a table format with pagination and sorting capabilities. I have chosen the DataGrid component from Material UI, but I am encountering some errors. Below is the code snippet: import React from 'react&apos ...

'this' while being utilized in a nested function

const EventEmitter = require('events').EventEmitter; const Counter = function (init) { this.increment = function () { init++; this.emit('incremented', init); } } ...

How can I assign a specific class to certain elements within an *ngFor loop in Angular?

I have a situation where I am utilizing the *ngFor directive to display table data with the help of *ngFor="let record of records". In this scenario, I am looking to assign a custom CSS class to the 'record' based on specific conditions; for exam ...

XMLHttpRequest failed to load the specified URL because the 'Access-Control-Allow-Origin' header was not found on the requested resource

When attempting to make an XMLHttpRequest to , I encountered an issue. The request to was blocked due to the absence of an 'Access-Control-Allow-Origin' header. This prevented access from the origin 'http://localhost', resulting in an ...

Tips for inserting items into an array of objects?

I have an array of objects with categories and corresponding points, and I need to calculate the total points for each category. { category: A, points:2 }, { category: A points: 3 }, { category: B, points: ...

Storing the DOM in a Variable

I have saved the response of an XMLHttpRequest() into a variable from a specific website, let's say yahoo.com. How can I retrieve the values of the DOM content using either getElementById or getElementsByName on this variable? For instance: var dump ...

Enhance npm package by implementing custom functionality with React Component

I have designed an app that bears a striking resemblance to the following code: class MyCustomApp extends React.Component { constructor (props) { super(props) this.state = { tags: [ { id: 1, name: "Oranges" }, { id: 2, ...

What is the Angular2 version of angular.equals?

Currently, I am in process of upgrading an Angular 1 project to Angular 2. In the old project, I used angular.equals for comparing objects like this: angular.equals($ctrl.obj1, $ctrl.newObj);. I tried looking online for a similar method in Angular 2 but ...

"The text() or json() methods in Javascript's fetch function never seem to resolve, leaving the operation in a perpetual

In my new nextjs 13 project, I'm attempting to perform a fetch operation (unsure if it's related to JavaScript or nextjs) and using console.logs to monitor the code execution. let url = `${BASE}/${module}/${path}`; url += "?" + ne ...

Skip over specific entries while using ng-repeat

This is how I have structured my ng-repeat: <div id="popular" ng-repeat="m in mods"> <!-- content goes here --> </div> <div id="personal" ng-repeat="m in mods"> <!-- more content here --> </div> The contents ...

Is there a specific index range in javascript or nodejs for accessing array items?

I recently came across this Ruby code snippet: module Plutus TAX_RATES = { (0..18_200) => { base_tax_amount: 0, tax_rate: 0 }, (18_201..37_000) => { base_tax_amount: 0, tax_rate: 0.19 }, (37_001..80_0 ...

Tips for efficiently updating state in React.js dynamically?

Is there a way to dynamically update the state of CurrentIndex whenever a user is selected? Currently, it is hardcoded to 0 but I would like to change that. I need the currentIndex to be updated whenever a user from the list is clicked. The SidePan ...

"Download content for offline viewing without the need to create a player object using shaka player

Class: shaka.offline.Storage This class includes a constructor. new Storage(player) Class: shaka.Player This class also has a constructor. new Player(video(non-null), opt_dependencyInjector(opt)) However, my goal is to save a video URL without a vide ...

JavaScript array with more than 4 elements

I am working on a program where I have created an array and now want to display all the words that contain more than 4 letters. Check out my code snippet below: function oppC(){ var ord = ["Apple", "Two", "Yesterday", "mother", "lol", "car", "co ...

Having trouble opening a JPEG file that was generated using the Writefile Api in Ionic-Cordova

Currently, I am using the writeFile API to create a JPEG image. The process is successful and the image is stored in the directory as expected. However, when I try to open the file manually from the directory, I encounter an error message saying "Oops! Cou ...

React Component that closes when it loses focus

In my React project, I am working on creating a custom select2 style component. Most of the functionality is complete, but I am struggling with figuring out how to hide the result box when the user clicks away. Here is the render method: render() { l ...

An AngularJS Dilemma: Troubleshooting JSON Integration

I am working with a JSON source and trying to fetch results from it using a post request. Interestingly, when I use the POSTMAN extension in Chrome, everything works perfectly fine. However, when I try the same thing with AngularJS, the page keeps loading ...