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

Angular JS allows for the display of text from a textarea upon clicking the submit button

Q] How can I display a single text message from a textarea upon clicking the submit button in angular-js? Here is the current code that I have: <html ng-app="myApp"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1 ...

Is it possible to shift the image within the <canvas> element without having to redraw the entire canvas?

I created a game board and I am trying to implement drag-and-drop functionality for my pieces, which are in .gif format. However, I am struggling with finding a solution that allows me to move the pieces without constantly redrawing the entire board. Cur ...

Modifying the text within the label of a multibarchart in nvd3.js

After analyzing the multibarchart in nvd3.js, I have discovered that it requires a specific JSON format as input. [ { "key": "abcd", "values": [ { "x": 1221578789000, "y": 40 }, { "x": 1222578789000, ...

Retrieving the NorthEast and SouthWest regions with AngularJS

Check out my code on the fiddle page linked below. I am having trouble with the South West and North East coordinates for the map and markers. View the code fiddle here I attempted to solve this issue, but it did not work as expected. var bounds = map ...

Is incorporating re-routing into an action a beneficial approach?

My main concern involves action design strategies: determining the best timing and method for invoking actions. In my project using Mantra (utilizing React for the front-end and Meteor's FlowRouter for routing), there is a UI component that includes ...

Seemingly the Tailwind Styles are failing to take effect in my Next.js Project

While following a Next.js tutorial project, I ran into an issue where my project seemed to be way off. It appeared that the tailwind styles were not being applied for some reason, even after tweaking the 'tailwind.config.js' file without success. ...

I am facing an issue with uploading files to my designated directory through Node.js Multer

After creating a web service using node js and implementing a form with React interface that includes user information and file upload, I encountered an issue while attempting to save the file to the specified directory on the node js server using multer. ...

Utilizing TypeScript generics to accurately extract type information from state during reduction

In the context of a state reducer presented as follows: const anObject = { fruit: 'Apple', today: new Date(), } function reducer(state, stateReducer) { return stateReducer(state); } const fruit = reducer(anObject, state => state.fruit ...

Top method for displaying and concealing GUI elements upon a click event

I would like a dat.GUI() instance to appear when a mesh is clicked, and disappear when it is clicked again. Furthermore, if it is clicked once more, I want it to reappear. Despite trying various approaches, I have been unable to achieve the desired behavio ...

Avoiding node_modules in Webpack 2 with babel-loader

After updating to Webpack 2, I've run into an issue with the "exclude" property in my "rules". It seems I can no longer pass "exclude" into "options". What is the correct approach to handling this now? Previously: { test: /\.js$/, loader: ...

Exploring the Angular framework: Combining form requirements and controllers in directives' link functions

In my coding journey, I have developed a powerful directive known as formNavHandler. This directive plays a crucial role in handling dirty checking and smooth navigation between different pages. The functionality of formNavHandler heavily relies on the exp ...

What is the process for converting an Angular UTC timestamp to a local timestamp?

Is it possible to convert a UTC timestamp to a local time timestamp using any function or method? I am sending the timestamp to angular moments, but the server's timestamp is in UTC. ...

Organizing subcategories within a dropdown checklist

I am currently working on a list that utilizes dropdownchecklist and I am looking to create subgroups from the elements in the list. The goal is that by clicking on a subgroup checkbox, it will automatically check all elements associated with it. Below is ...

What is the most effective method for implementing COPY/INSERT functionality with cascading effects in PostgreSQL?

Seeking advice on the most effective method to perform an "on cascade copy/insert" of linked elements within PostgreSQL. To better explain my scenario, I've crafted a straightforward example: Understanding the Database Structure Within the datab ...

Guide on how to forward the response obtained from an Ajax call to a different HTML page

I am working with a mongoose database that stores data containing an individual's first and last name. The user inputs their first name into a field, triggering an ajax request sent to the file named controller.js. This file generates a JSON response ...

Initiate node.js execution upon system boot

Just diving into node.js. In the process of setting up integration tests for a node.js app using mocha, I found this helpful guide: Here's how I created a server: var http = require('http'); this.server = http.createServer(function (req, ...

What is the procedure to obtain a session object on the server side in next.js version 14?

I am currently utilizing version 14 of next.js with its app routing feature and NextAuth. My goal is to secure the API, however, I encounter a null object when using the getServerSession( authOptions ) method while attempting to access a protected endpoin ...

What could be causing the .text method to not retrieve text even when it is present?

Currently experimenting with web scraping using Selenium to extract the color of a particular dress. Despite finding the text content under the 'screen-reader-text' class when inspecting the website, my attempts at fetching it result in an empty ...

What is the process for dynamically declaring a variable within the data function in Vue.js?

Looking for a solution where I can have the ability to dynamically add input fields to a form. Currently, my form consists of three input fields - name, email, and phone. However, I would like users to be able to add more input fields as needed. In order t ...

Tips for including an element at the start while creating a map()

enum StatusEnum { accepted = "AC", rejected = "RJ", } const select = (Object.keys(StatusEnum) as Array<keyof typeof StatusEnum>).map((x) => ({ value: x, name: x + "_random", })) /** * Console.log(select) * [ ...