Angular will compute an expression whenever it is assigned as a property

Consider this example:

    $scope.element =
            {
                html: '<a type="button" class="btn btn-xs btn-rounded m-r-sm"><i class="icon icon-user-unfollow"></i></a>',
                classExpression : " {{inactive == 'true' ? 'btn-success': 'btn-danger'}}",
            }

In the code above, there is a variable named classExpression which I want to add to the element.

 <span  ng-bind-html="element.html | trust" class="{{element.classExpression}}">Text in between<span>

Unfortunately, it does not get evaluated as expected.

My question is, how can this be achieved (if it is even possible)?

Check out my fiddle for reference.

I have updated my fiddle as it wasn't working correctly before.

Answer №1

It would be beneficial to update the structure of your object in the following way. It is not recommended to include expressions in a string.

HTML

<span ng-bind-html="element.html" ng-class="element.classExpression[element.inactive]">
    Text in the middle
</span>

Code

$scope.element = {
    html: '<a type="button" class="btn btn-xs btn-rounded m-r-sm"><i class="icon icon-user-unfollow"></i></a>',
    classExpression: {
      'true': 'btn-success',
      'false': 'btn-danger'
    },
    inactive: 'true'
};

Forked Fiddle

Answer №2

Instead of binding ng-class to the element expression, have you considered using it directly? This way, it will be re-evaluated whenever your scope.inactive changes. Alternatively, you could bind the inactive property to your element.

For example:

<span ng-bind-html="element.html | trust" ng-class="{'btn-success' : element.inactive, 'btn-danger' : !element.inactive}">Text in between<span>

In Angular 1.1.4 and newer versions, you can also use the ternary operator:

<span ng-class="element.inactive ? 'btn-success' : btn-danger">

In this case, assuming you have bound the inactive property to your element, you can directly bind it (on scope) instead.

Answer №3

To successfully update your code, you must eliminate {{ }} from the 'classExpression' section as shown below:

 classExpression : " inactive == 'true' ? 'btn-success': 'btn-danger'"

Additionally, ensure to incorporate ng-class in the following manner:

ng-class="{{element.classExpression}}"

Answer №4

Consider converting your classExpression into a function:

$scope.element =
        {
            html: '<a type="button" class="btn btn-xs btn-rounded m-r-sm"><i class="icon icon-user-unfollow"></i></a>',
            classExpression : function(){
                return $scope.inactive == 'true' ? 'btn-success': 'btn-danger';
            }
        }

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

Activate a live search jQuery plugin using JavaScript

Currently, I have integrated the jQuery live search plugin created by Ryan Heath into my website. In order to enhance user experience, I decided to include three checkboxes which allow users to select their preferences for searching. However, I am faced wi ...

Issues with NodeJs Express routes execution

After testing, I found that only the default route "/" is working in my code. Many similar issues involve routers being mounted to paths like "/auth" or "/user". Even when I tested the default router mounted to "/", it still isn't functioning properly ...

Using HTML5 Canvas to draw intersecting polygons

Recently, I came across a polygon drawing function that caught my attention: Polygon.prototype.draw = function(ctx) { ctx.save(); ctx.beginPath(); var v = this.vertices[0] ctx.moveTo(this.position.x + v.x, this.position.y + v.y); var i ...

Is there a way for ResponsiveSlides to fade the pager without causing any disruption to the content below, all

I have been working with the Responsive Slides jQuery plugin and made some custom modifications. Everything is going smoothly, but I am facing an issue with getting the pager and next/prev controls to fade in when hovering over the container. Although I s ...

Is it possible to create a unit test for a JavaScript function that manipulates an HTML element?

I'm struggling with testing a function that includes a modal displayer like this: function modaldisplayer(){ $('.mymodal').modal('show'); return 'success'; } In my code, there is another function called 'foo&a ...

What is the syntax for sending a DELETE request in MongoJS?

I've been working on a simple contact list app and encountered an issue with deleting a record. When I press the delete button, it stops the server but upon restarting it, the record is successfully deleted (the correct list is displayed). The GET an ...

Locate the initial hidden element using jQuery

HTML: <div style="display:block">Text</div> <div style="display:block">Text</div> <div style="display:none">Text</div> <div style="display:none">Text</div> <div style="display:none">Text</div> W ...

Uncovering data from a dynamic website through the combination of Selenium and PhantomJS

I am attempting to obtain the timer value from this website http://prntscr.com/kcbwd8 located at , and ideally save it in a variable. import urllib from bs4 import BeautifulSoup as bs import time import requests from selenium import webdriver from urllib. ...

Transforming Javascript code using regular expressions into C#

Currently, I am facing a challenge while trying to translate some Javascript code into .NET. Despite my efforts, I have not been able to get it right. The task at hand involves converting paths like /test/:value1/:value2 in Express for NodeJS to a regular ...

Utilizing React.js for displaying a collection of items

I have been working on a simple React program that involves displaying a button to the user. Upon clicking the button, an API call is made and the results are displayed in a list format. Although I have reached a point where I can successfully fetch and m ...

Adjust the tooltip image alignment to be offset from the cursor and appear at the bottom of the page

After creating a code snippet for image tooltips on text hover, I encountered an issue on my website where the bottom of the page expanded to accommodate the images. Is there a simple way to align the cursor at the bottom of the image when scrolling to the ...

"Issues with Angular ng-show Functionality on Internet Explorer Versions 7 and

I'm currently working on a feature where I need to show or hide two divs conditionally using ng-show based on the completion of an AJAX call. The layout for this includes: <div id="div1" ng-show="!loadingData"> <!--Some markup here--> ...

Unexpected anomaly with Jquery's after() method

Currently, I am working on the following task: I want to dynamically add a new student to a table of existing students using AJAX when a student is added through my user interface. The process involves sending the UI input fields to the controller, which ...

Tips for assigning an AngularJS data-bound value to the href attribute of an anchor tag

I need to include multiple email ids separated by commas from an angularjs binded value in the mailto field of an anchor tag. The team.emails variable can contain either a single email id or multiple email ids separated by commas. <tr ng-repeat="team ...

Deploying React application to Heroku resulted in an Application Error even though there were no errors during the build

I'm facing some issues while deploying my React app on Heroku. Even though the app compiles and builds successfully on both my local server and Heroku, it still shows an error. I've added https://github.com/mars/create-react-app-buildpack.git to ...

Display a loading bar or prevent any user interface actions until the server has finished generating the file

I am currently developing a force directed layout using d3.js on data retrieved from an MS SQL server database. I'm creating the json file with a python script and running it on a local server using python -m SimpleHTTPServer. My goal is to establish ...

problem with concealed picture when hovering cursor

While I know this issue has been discussed before, I am facing a slight confusion regarding displaying an image on MouseOver. Currently, I have a div container with a colored background that shows when hovered over. You can see an example of this here - sc ...

What's causing this error message to appear? "View 'index' not found in the views directory '/app/views'"

I'm currently working on deploying my Angular app to Heroku. It's running smoothly on my local environment. Here is the directory structure: nice-notes controllers api.js index.js Model model.js public main.js main.css views ind ...

Delete the last TD before adding the new element

Below is a snippet of jQuery code that I am working with: html += '<tr>'; html += '<td>AAA</td>'; html += '<td>BBB</td>'; html += '<td>CCC</td>'; html += '<td>DDD ...

Updating the default date format input fields for React-bootstrap-daterangepicker in the United States

Hey there, I'm a newcomer to the world of React and Javascript and I've encountered an issue that has me stumped. I'm trying to change the default US dateformat in my React-bootstrap-daterangepicker, but I'm struggling to figure out how ...