Modify components in a directive template depending on the information in the scope

In my project, I am facing an issue with a directive nested within an ng-repeat. The ng-repeat item is passed to the directive and I am trying to generate a directive template or templateUrl with dynamic elements based on a key/value in the item. Specifically, I want to make a button red if the item number is greater than 50, otherwise blue.

I suspect that I might not be using the right approach to solve this problem. My aim is to modify Bootstrap tags based on certain conditions. For example, I would like to apply the logic:

if item.number > 50: 
  class="btn btn-danger"
else:
  class="btn btn-success"

If possible, I prefer using templateUrl as I need the button to trigger a bootstrap modal which might be difficult to incorporate in the basic template option. Passing individual scope variables to the template seems like a cleaner solution.

You can check out this JSFiddle link for more context on the problem.

Here is the HTML snippet:

<div ng-controller="TableCtrl">
  <table>
    <thead>
      <tr>
        <th>#</th>
        <th>Button</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in buttons">
        <td>{{item.id}}</td>
        <td new-button item='item'></td>
      </tr>
    </tbody>
  </table>
</div>

And here is the corresponding JavaScript code:

var myApp = angular.module('myApp', []);

function TableCtrl($scope) {
  $scope.buttons = {
    button1: {
      id: 1,
      number: '10',
    },
    button2: {
      id: 2,
      munber: '85',
    }
  };
};

myApp.directive('newButton', function() {
  return {
    restrict: 'A',
    replace: true,
    scope: {
      item: '=',
    },
    link: function(elem, attrs, scope) {
        // This is most likely not the right location for this
        /*if (item.number > 50) {
        button.color = red
      }, else {
        button.color = blue
      }; */
    },
    template: '<td><button type="button">{{button.color}}</button></td>'
  }
});

Answer №1

If you want to style a button based on a condition, consider using the ng-class directive like so:

<button ng-class="{
  'btn-danger': item.number > 50,
  'btn-success': item.number <= 50
}"></button>

For more information, check out the documentation at https://docs.angularjs.org/api/ng/directive/ngClass

Answer №2

If you find yourself in need of a personalized directive, one option is to implement it in the following manner:

link: function(scope,elem,attrs) {
        var item=scope.item;
        if (item.number > 50) {
        elem.addClass("btn-danger");
      } else {
        elem.addClass("btn-success");
      }
    }

However, I believe that the ngClass directive would be more suitable for your specific requirements, as demonstrated below:

<button type="button" item="item" class="btn" ng-class="item.number > 50?'btn-danger':'btn-success'"></button>

Answer №3

Upon reviewing your sample code, I have identified a few key points:

  1. There is a typo in the 'munber' property of button 2.
  2. The link function lacks dependency injection, so the argument order is significant. Scope should be prioritized first.
  3. Your commented-out section of code is almost functional, but you must reference the variables as scope properties - 'item' should be on scope, and the button object you create needs to be scoped to be addressed as 'button' in your view template.

This implementation works (although using ng-class instead of class with moustache syntax, as suggested by others, would be more optimal):

HTML

<div ng-controller="TableCtrl">
  <table>
    <thead>
      <tr>
        <th>#</th>
        <th>Button</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in buttons">
        <td>{{item.id}}</td>
        <td new-button item='item'></td>
      </tr>
    </tbody>
  </table>
</div>

JS

var myApp = angular.module('myApp', []);

function TableCtrl($scope) {
  $scope.buttons = {
    button1: {
      id: 1,
      number: '10',
    },
    button2: {
      id: 2,
      number: '85',
    }
  };
};

myApp.directive('newButton', function() {
  return {
    restrict: 'A',
    replace: true,
    scope: {
      item: '=',
    },
    link: function(scope, elem, attrs) {
        scope.button = {};
        if (scope.item.number > 50) {
        scope.button.class = 'btn btn-danger';
      } else {
        scope.button.class = 'btn btn-success';
      };
    },
    template: '<td><button type="button" class="{{button.class}}">Press Me?</button></td>'
  }
});

CSS

.btn-danger {
  background-color: red;
}
.btn-success {
  background-color: green;
}

Modified JSFiddle

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

JavaScript Function to Retrieve URL Parameter in PHPIn this tutorial

I'm currently working on an HTML5 game where each level has its own dedicated HTML page. The results of each level are saved in a JavaScript variable. My question is, how can I pass this information to the next page using the URL? I was considering ...

Enhancing code with new Javascript functionality

Currently utilizing the WordPress Contact Form 7 plugin and in need of updating my existing JavaScript code to include an onclick function and data-img attribute for checkboxes. Due to the limitations of Contact Form 7 shortcode, adding attributes beyond i ...

Performing an XMLHttpRequest to Submit an HTML Form

Our Current HTML Form Setup This is an example of the HTML form we are currently using. <form id="demo-form" action="post-handler.php" method="POST"> <input type="text" name="name" value=" ...

Struggling with implementing jQuery AJAX in Node.js Express - any tips?

Struggling with implementing ajax in node js for the first time. I've been testing it using the console, but unable to get a response. Here's my code: <script> function getMessage() { var data = $("#messageselect").val() $.ajax({ ...

Tips for sending a URL in form-data as a file with JavaScript or Axios

Currently, I am using Vue.js and Axios to send form data to a specific link. However, I encountered an issue where the file is not being sent and I am receiving an error message. The parameter 'file' had the following problems: file transferred w ...

The react-native-video-controls package was used in React Native. When the onBack event was triggered, it successfully navigated back to the initial screen. However, upon returning

https://i.stack.imgur.com/GsS3d.png https://i.stack.imgur.com/HYBOU.png Attached are screenshots showing the issue I am experiencing with my video player. When I click the back button, the screen does not return to its initial state and the flatlist items ...

Guide to making a vertical clickable separator/line using bootstrap

Seeking advice on creating a layout where the left side consists of a sidebar menu occupying 24% and the right side contains main content taking up 75%, with a clickable vertical divider at 1% between them. When this line is clicked, the left part will hid ...

Tips on revealing TypeScript modules in a NodeJS environment

Currently, I am working on developing a TypeScript library. My goal is to make this library compatible with both TypeScript and JavaScript Node projects. What would be the most effective approach for achieving this? Should I create two separate versions ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...

Issue with `npm run watch` failing to compile when the data source is turned

Currently, I am faced with a challenge while working on Laravel and utilizing various node packages for development. The issue at hand is my limited internet connectivity. Every time I attempt to execute npm run watch, it refuses to initiate unless I am c ...

Upon clicking the link, the JavaScript functionality failed to activate

When I click on a link and try to add a class, it's not working. I want to create a "modal" div. Here is the PHP/HTML code: <?php if(isset($_GET['ido'])) { ?> <div id="modal" class="modal" style="background: blue; width: 1 ...

Struggling to generate a cookie through an express middleware

I'm currently working on setting up a cookie for new user registrations in my app to track their first login attempt. I came across this thread which provided some guidance but I'm still facing issues. Below is the snippet of my code: // Middle ...

Not adhering to directive scope when transclusion is used, despite explicit instructions to do so

Trying to use a transcluding directive within another controller, but the inner scope isn't being redefined as expected. Despite trying different methods, I can't seem to figure out what's going wrong. The simplified code looks like this: ...

In some cases, ui-router may fail to navigate to a different page on Internet Explorer versions greater than 9

Currently, I am utilizing ui-router for my application. Interestingly, in Internet Explorer versions above 9, the page routing functionality seems to cease working at times. This issue is particularly prominent when I manually modify the URL path and pre ...

Pattern matching: Identify text elements specifically within an HTML tag

I've been experimenting with a text highlighting script. Check out my initial attempt here. Here's the code snippet: http://jsfiddle.net/TPg9p/3/ However, I encountered a problem – it only works with simple strings and not those containing HT ...

The table row disappears but the value persists

I have designed a table where users can perform calculations. However, when a row is deleted, the values from that row appear in the row below it and subsequent rows as well. What I want is for the user to be able to completely remove a row with its values ...

I am interested in creating a ranking system in JavaScript using JSON data based on points

I have a desire to create the following: var users = {jhon: {name: 'jhon', points: 30}, markus:{name: 'Markus', points: 20}}; // I want it to return like this 1. Jhon with number of points: 30 // 2. Markus with number of points: 20 ...

There is an issue with the functionality of Java code that has been adapted from Javascript logic

I'm currently using NetBeans8 IDE. Check out this java script function from this Fiddle function animate() { xnow = parseInt(item.style.left); item.style.left = (xnow+1)+'px'; ynow = parseInt(item.style.top); item.style. ...

Is it possible to keep content visible in Bootstrap tab by adding CSS?

Having an issue with the "formbox" class that is causing unexpected behavior when applied to a form. When removed, everything works as expected. I've tried narrowing down the issue by removing each CSS rule individually and testing it out but haven&ap ...

Button Click Not Allowing Webpage Scroll

I am currently in the process of developing a website that aims to incorporate a significant amount of motion and interactivity. The concept I have devised involves a scenario where clicking on a button from the "main menu" will trigger a horizontal and ve ...