Conditions in Controller Made Easy with AngularJS

I have recently started working on implementing a notifications feature. The service will involve making a GET request to a specific URL which will then return an array of notifications.

Within the controller, I am in the process of setting up a variable that will hold a message string for each different notification type. Since I am still new to Angular, I just want to confirm if my syntax and logic are correct.

/* Model + Controller */
// Assume this code is wrapped in a controller function

$scope.notifications = notifications=[
{id:1, type: 6},
{id:2, type: 3},
{id:3, type:4}]; 

$scope.display_message = function(){

    if ($scope.notifications.type == 1){

    $scope.notification_message = "some text";

    } else if ($scope.notifications.type == 2){

    $scope.notification_message = "some text";

    }

  //... additional logic for brevity

return $scope.notification_message

}


/* View */

<li ng-repeat={{notification in notifications}}>

    {{display_message()}}
</li>

Answer №1

It seems that the logic here is a bit confusing, but it appears that the intention is to display a message for each notification, requiring passing the notification each time.

// Inside a controller function

$scope.notifications = notifications=[
{id:1, type: 6},
{id:2, type: 3},
{id:3, type:4}]; 

$scope.display_message = function(notification){

    if (notification.type === 1){

    $scope.notification_message = "some text";

    } else if (notification.type === 2){

    $scope.notification_message = "some text";

    }

  //... for simplicity sake

return $scope.notification_message

}


/* View */
<li ng-repeat="notification in notifications">

    {{display_message(notifcation)}}
</li>

Additionally, it is advisable to remove the {{}} in ng-repeat, and always use === instead of ==.

Answer №2

When $scope.notifications is an array, how can you determine if $scope.notifications.type equals 1?

You may want to consider the following approach:

$scope.displayMessage = function(notification) {
    var message;
    
    if (notification.type == 1) {
        message = "some text";
    } else if (notification.type == 2) {
        message = "some other text";
    }
    
    return message;
}

Then in your HTML:

<li ng-repeat="notification in notifications">
    {{displayMessage(notification)}}
</li>

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

Steps for integrating external modules into an AngularJS single page application without using injector/modulerr

As a newcomer to AngularJS, I've been facing challenges when following tutorials and incorporating external modules. I have some concerns about avoiding injection errors. Q1. How can I resolve the injector/module issue? I used bower to install ' ...

Can an infowindow be automatically closed based on specific criteria?

Show the infowindow only when hovering over the marker. It should disappear when moving the mouse away from the marker. The infowindow should stay open only if you click on the marker, and can be closed by clicking the close button on the infowindow. ...

Ways to launch angularjs project in production mode sans the use of npm start

Currently, I am in the process of developing a website with angularjs and have set up a local development server using npm. After moving my project directory to a public AFS directory, I encountered an issue where the npm dependencies are not functioning ...

Benefits of Utilizing Object.create

Unlike the referenced question, this code snippet is sourced from the book "JavaScript: The Definitive Guide". It introduces an inherit method that applies Object.create if available, but falls back to traditional JavaScript inheritance when it's not. ...

Using the ref callback to access getBoundingClientRect values in React Components

I'm having some trouble extracting data using the getBoundingClientRect() method from a set of animated div elements. The issue I'm facing is that the refCallback function is returning empty DOMRect objects. If you're interested, feel free t ...

When Infinite Scroll is integrated into another file with HTML tags stacked on top, it will not load additional posts when scrolling down

I have implemented an Infinite Scroll feature that dynamically loads more data from a database as users scroll to the bottom of the page. However, I encountered an issue when trying to include this functionality in another .PHP file. If I insert any HTML ...

Guide to creating standalone Express middleware that can interact with the raw request body

Can anyone help me with writing an Express middleware that can access the raw request body without affecting other handlers or middlewares? I want to achieve something like this: const middleware = [ express.raw({ type: '*/*' }), (req, res, n ...

Learn how to efficiently execute a function multiple times using pure JavaScript

I am trying to create a tabbed content functionality with multiple elements. How can I utilize the same function for various elements declared in a variable? For example, I want to clone the parent div.tabs element with similar content but different ids an ...

Is there a way to search for a specific item within a nested array?

I have 2 arrays within an array, each containing objects. How can I locate the object with the name "Sneijder"? const players = [ [ { id: 1, name: "Hagi", }, { id: 2, name: "Carlos", }, ], [ { id: 3 ...

Acquiring an alternative data structure in JavaScript or JSON

When clicking on a div with different attributes, I am attempting to retrieve a data object. Here is an example: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var locA = { "fro ...

Utilizing Kendo Grid for client-side data paging

I am looking to utilize an MVC helper for constructing a grid on the server side, with the ability to dynamically add and remove rows on the client side. To achieve this functionality, I have implemented the following wrapper: @(Html.Kendo().Grid<SIGE ...

Top method for achieving a smooth transition in a loading CSS3 animation

Having trouble implementing a fade in/fade out effect on a div with a CSS3 based login animation when a function is loaded. I have set up a jsfiddle but still can't get it to work. Any assistance would be greatly appreciated! http://jsfiddle.net/adam ...

What is the best way to incorporate the value of a textbox into a list?

I currently have a list structured like this: <p>Please choose from the following options:</p> <script type="text/javascript"></script> <select id='pre-selected-options1' multiple='multiple'> <opt ...

Is there a way to filter out only the objects from the JSON data and exclude the strings?

I am facing an issue while looping through a JSON object. The presence of strings in the JSON is causing the loop to fail. How can I iterate only through the objects in the JSON without affecting the loop? My main goal is to iterate through the objects co ...

Top method for combining several external JavaScript libraries into a single one using webpack

Recently, I was diving into the world of webpack tutorial and it struck me that in order to combine everything into one module, scripts need to use require('./xyz'). Until now, I've always written individual scripts and loaded them in HTML u ...

Angular dynamic calculations for min and max values result in an unusual user interface

I am encountering an issue with a datetime-local input field that has max and min attributes. <input type="datetime-local" ng-model="model.date" min="{{min}}" max="{{max}}"> These attributes are dynamically set based on the date from another input ...

AngularJS ngTable Error Detected

When using ngTable (AngularJS) to display a list of elements, an error arises during compilation: ************ I am OK ****************** articles.client.controller.js:12 ReferenceError: articles is not defined at new (...../modules/articles/controlle ...

Is there a more efficient method for translating arrays between JavaScript and PHP?

Currently, I am in the process of developing a web page that has the capability to read, write, and modify data stored in a MySQL database. My approach involves utilizing PHP with CodeIgniter for handling queries while using JavaScript to dynamically updat ...

What is the reason behind JavaScript events causing a page refresh?

My code uses RegExp to search through an array of strings based on user input: Clinica.prototype.pesquisarDoente = function () { var exp = document.getElementById("pesquisaInput").value; var lista = document.getElementById("listaDoentes"); if ...

Converting the length attribute of a table to a string does not yield any

After grappling with this bug for some time now, I've come up empty-handed in my search for a solution online. Expected Outcome: Upon pressing the create row button, I anticipate a new row being added at the bottom of the table. This row should cons ...