Error: Issue transferring data to controller from Ng-Style

Currently, I am developing an application using Ionic and AngularJS. In this project, I am using ng-repeat to populate the results and want to display different colors based on certain criteria.

Initially, I managed to achieve this using inline ng-style coding for one specific criterion:

<table ng-style="{color:(test.Status == 'Cleared')?'green' : 'red'}">

Although this method works perfectly fine, it becomes impractical when I need to set multiple criteria like time and others.

Therefore, I attempted to move this functionality to the controller using the following approach:

<ion-list>
  <ion-item ng-repeat="test in tests" class ="item-text-wrap" style="height:40%">

    <a href="#/tab/test/test-detail/{{test.ID}}">
    <div style="width:80%; float:left;">

    <table>
    <span ng-style="calculateStyle(test)">
    <tr>
        <td> <strong>Remark: </strong></td>
        <td style="padding:3px">{{test.Remark}}</td>
    </tr>
    <tr>
        <td><strong>Status:</strong></td>
        <td style="padding:3px">{{test.Status}}</td>
    </tr>
        </span>
    </table>

</div>
</a>
</ion-item>
</ion-list>

Inside my controller class:

.controller('Ctrl', function($scope, $http, $cordovaSQLite, dataFactory, StoreService) {
....
  $scope.calculateStyle = function(test) {
      var style={}
      if (test.Status  == 'Cleared') {
      style.color='green';
      console.log('Success');
    }
    else{
      console.log('Error');
    }
      return style;
  }

It's important to note that the 'tests' data is retrieved from a JSON web service and consists of multiple objects, hence the use of ng-repeat to loop through each test object for color coding purposes.

However, I encountered an error message:

Uncaught SyntaxError: Unexpected token test

at the line:

$scope.calculateStyle = function(test) 

If I pass an integer or string to calculateStyle('Test') or calculateStyle(123), it works fine. The issue arises only when passing 'test' as an argument. Any suggestions on how to resolve this problem?

I also attempted to replace it with '$scope' but without success. What could be causing this issue?

Thank you!

Answer №1

Employing

<div ng-init="variable = method" ng-style="changeStyle(variable)"> 

gets the job done.

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

Tips for overcoming indentation issues using ESLint?

Ever since I started using Vue 3 with ESlint, I've been encountering a new problem. Whenever I try to run my code, I am bombarded with numerous errors like: --fix option.</p> I'm looking for ways to disable this troublesome feature of ESl ...

Ensure that all links are opened in a new tab

When including _blank in the a href URL, my website contains various elements like iframes and ads from Adsense, Taboola,, etc. Currently, when a user clicks on an iframe or ad, it opens in the same window. Is there a way to ensure that all URLs (includin ...

Calculating the total number of clicks on a button using PHP

I am attempting to track the total number of clicks on a button by individual users, rather than combining all members' clicks. Each user's clicks on the button should be logged separately. I am struggling to determine the best approach for this ...

Issue encountered when attempting to establish a new loadingController with LoadingOption

Hey there, I am relatively new to Ionic and I encountered an issue while trying to create a new loading screen. Argument of type '{ content: string; }' is not assignable to parameter of type 'LoadingOptions'. Object literal may only s ...

The value of the checked input with the name `nameofinput` is currently not defined

I'm having trouble passing the input value to another page. $( this ).attr( "href", '?module=module_progress_report&Subject='+ $('input[name=subject]:checked').val()+ '&Centre_Selected_ID='+ encodeURIComponen ...

Tips on how to automatically resize the browser window to a specific width and height once it has been minimized

If a JSP page is minimized onload, we need to find a way to restore it through a JavaScript call. Are there any other methods available for achieving this? The restoration should be to the height and width selected by the user. I have attempted the followi ...

Endless jasmine timeout

This question is a continuation of a discussion on the Remove timeout for single jasmine spec GitHub issue. Query: Can a single test be configured to never time out? The Issue: While it's possible to set a global timeout value using DEFAULT_TIMEOU ...

Exploring the possibilities of reading and writing data in localStorage?

Just starting out with Phonegap, jQuery Mobile, and HTML5 - so please bear with me as I navigate through this learning process! I'm having an issue and could use some help. When trying to use a variable from localStorage, the screen remains blank whe ...

Instantaneous data refresh using Firebase Cloud Functions

Currently, I am working on developing a chat feature in React using Firebase cloud functions. However, I am facing an issue where I do not receive updates when a user sends a message. Below is the code snippet that I have been working with: const app = a ...

Adjust the appearance of a div according to the input value

When a user inputs the correct value (a number) into an input of type "number," I want a button to appear. I attempted var check=document.getElementById("buttonID").value == "1" followed by an if statement, but it seems I made a mistake somewhere. Here&ap ...

I need to search through a tree structure in typescript based on a specific value without encountering a maximum stack call exceeded error

How can I perform a value-based search on a complex tree structure in TypeScript without encountering the maximum stack call exceeded error? I am attempting to navigate through an expandable tree using TypeScript, and I will provide the code snippet below ...

Is there a way to implement absolute imports in both Storybook and Next.js?

Within my .storybook/main.js file, I've included the following webpack configuration: webpackFinal: async (config) => { config.resolve.modules = [ ...(config.resolve.modules || []), path.resolve(__dirname), ]; return ...

The most effective method for adding a new key/value pair to a nested object

Currently working with React and attempting to add a new key-value pair to an object. I have an if check that verifies a condition, and if it is met, I want to include the key 'author'. if (field.component === 'Author') { this.pro ...

Struggling to retrieve data from Firebase in React Native?

It's been a challenge for me as a newcomer to React Native trying to retrieve data from a Firebase database. This is the process flow of how my data is handled: 1. A user selects locations and trip details (name, startDate, endDate) --> stored in ...

Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server? Here is an example in HTML: <div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)"> <p>drag one or more files to ...

Guide to activating the 'Next' button on WP Forms using JavaScript code when certain conditions are fulfilled

Is there a way to adjust the JavaScript code provided so that the visibility of the "Next" button is dependent on whether at least one item in the 'wpforms-icon-choices-item' class has the '.wpform-selected' class on the current page or ...

Tips for refreshing a webpage after switching screens

// I have implemented the code below to navigate from one screen to another, specifically the Home page. However, I am facing issues with the page refreshing or reloading when navigating to the home screen. None of the lifecycle methods are being called, e ...

Using Javascript to pass the value of a selected checkbox

I am having an issue with passing a row value to a different function when a user clicks on a checkbox in the last column of a table. The code I have written doesn't seem to be firing as expected. Can anyone help me figure out what might be missing in ...

What are the pros and cons of using a piped connection for Puppeteer instead of a websocket?

When it comes to connecting Puppeteer to the browser, you have two options: using a websocket (default) or a pipe. puppeteer.launch({ pipe: true }); What distinguishes these approaches? What are the benefits and drawbacks of each method? How do I know wh ...

Displaying text on hover and showing a text box when a link is clicked using CSS and JavaScript

Hovering over the text will display "Edit," and clicking on it will reveal a text box. This function will be used to update content using ajax. HTML: <table> <thead> <tr> <th> Name </th> <th> Age </th> ...