Trying to assign an array to $scope is causing issues

I have an array called `arr` in a function that I want to return to `$scope.notifications` so that I can use it in the HTML within the Ionic Framework. I want to use a function to perform certain actions with the array before returning it later on. Here is my controller:

.controller('notificationsCtrl', function($scope) {
    $scope.notifications = function(){
        var arr = [
            {user:"misterx", name:"Mister X", action:4, image: "https://www.holidaycheck.de/mediaproxy?target=hcaHR0cDovL3d3dy5ob3RlbC5kZS9tZWRpYS9ob3RlbC9waWN0dXJlcy8zMzQvMzM0MTIzL0V4dGVyaW9yXzYzNTkyNzk5NDMyODQ1OTAwMi5qcGc%3D"},
            {user:"misterx", name:"Mister X", action:2, image: "https://www.holidaycheck.de/mediaproxy?target=hcaHR0cDovL3d3dy5ob3RlbC5kZS9tZWRpYS9ob3RlbC9waWN0dXJlcy8zMzQvMzM0MTIzL0V4dGVyaW9yXzYzNTkyNzk5NDMyODQ1OTAwMi5qcGc%3D"},
            {user:"ladyx", name:"Lady X", action:1}
        ];
        return arr;
    }
})

The HTML:

<ion-item ng-repeat="msg in notifications" class="item-text-wrap">
    <div class="row">
        <div class="col-80">
            <strong>{{msg.name}}</strong> (<em>@{{msg.user}}</em>) {{msg.action}}.
        </div>
        <div class="col-20">
            <img src="{{msg.image}}" style="border-radius: 50px; width: 100%">
        </div>
    </div>
</ion-item>

When I directly pass notifications as an array without using a function, it works. What am I missing here?

Answer №1

When using ng-repeat="msg in notifications", it attempts to repeat over the function itself rather than its return value. To correctly iterate through the list, you should call the function like this:

<ion-item ng-repeat="msg in notifications()">

Visit this link for an example.

It's important to note that there may be performance issues with this method. The function will be called frequently because Angular cannot anticipate whether the function's result will change. It is recommended to store "notifications" as a regular array in the scope instead. Any changes made to that array will automatically prompt the component to re-render with the updated values:

  $scope.notifications = [{
    user: "misterx",
    name: "Mister X",
    //...
  }];

  $scope.addNotification = function() {
    $scope.notifications.unshift({
      user: "newguy",
      name: "New Guy"
    });
    // Angular will detect the change in notifications[] and re-render the component during the next $digest cycle
  };

Take a look at this link for a demonstration.

Answer №2

No function is required to return JSON format for the following code:

.controller('notificationsCtrl', function($scope) {
$scope.notifications = [
        {user:"misterx", name:"Mister X", action:4, image: "https://www.holidaycheck.de/mediaproxy?target=hcaHR0cDovL3d3dy5ob3RlbC5kZS9tZWRpYS9ob3RlbC9waWN0dXJlcy8zMzQvMzM0MTIzL0V4dGVyaW9yXzYzNTkyNzk5NDMyODQ1OTAwMi5qcGc%3D"},
        {user:"misterx", name:"Mister X", action:2, image: "https://www.holidaycheck.de/mediaproxy?target=hcaHR0cDovL3d3dy5ob3RlbC5kZS9tZWRpYS9ob3RlbC9waWN0dXJlcy8zMzQvMzM0MTIzL0V4dGVyaW9yXzYzNTkyNzk5NDMyODQ1OTAwMi5qcGc%3D"},
        {user:"ladyx", name:"Lady X", action:1}
    ];

}

})

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

I am having trouble printing because of document.write

Whenever I use javascript to create a document with document.write I include an iframe element then I try to print the contents using iframe.print() but nothing happens - no error message and no print dialog box. How can I successfully initiate a print ...

What could be causing my application to hang on my local server?

Recently, I developed a NodeJS and Express MVC (or perhaps more accurately VC) app. Initially, everything worked smoothly until I integrated express-validator and included the middleware in the app file. This caused my localhost to freeze, displaying a GET ...

Coordinating Multiple Angular $http Requests using $q and Managing Errors with $q.catch

Struggling with understanding the correct utilization of Angular's $q and JavaScript's promise API. As a newcomer to Javascript, it's possible I'm making a syntax error. This question appears similar, but isn't an exact duplicate. ...

Having trouble getting collision events to trigger in ThreeJS when using the PhysiJS physics engine?

When an object falls and collides with the ground, an alert box should pop up displaying the message "Box just hit the ground". However, there seems to be an issue as the alert box is not being created upon collision. Additionally, no relevant JavaScript ...

Tips for ensuring a specific statement is only executed after the completion of an Async loop

Is there a way to ensure that the function FinalExecution is only run after all Async calls within the forEach function have been executed? runFunction=()=>{ cart.forEach(async(i)=>{ await axios.get(`localho ...

Utilizing a function as an express middleware in a specific route

I've encountered an issue with my route where I have some messy code that I want to transform into middleware. However, the documentation provided by Express is a bit unclear and as a result, my code keeps throwing a 404 error. Is there a way for me ...

Angular Router is unable to recognize the provided URL

When my app is loaded, I need to perform some logic using the URL as a parameter. Currently, I am working on an Ionic 5 project and in my app.component.ts file, I have the following code: export class AppComponent { constructor(router: Router) { cons ...

Locating a specific element in javascript using its id

I'm struggling to automate the process of downloading a CSV file from a website using Selenium. Specifically, I'm having trouble selecting the format of the file and clicking on export. Does anyone have any ideas on how to accomplish this? To acc ...

preventing elements from moving unexpectedly as the navigation bar becomes fixed at the top of the page

I have a website that features a Bootstrap 3 navbar. This navbar is positioned 280px below a block div and becomes sticky at the top of the page when scrolled to that point. HTML (within < head > tags) <script> $(document).ready(function() ...

Clicking the Javascript styling toggle does not function properly on the initial click

I'm currently developing an HTML application with a sidebar menu that toggles on click. However, I've encountered an issue where the menu doesn't appear until the second click. The first click seems to have no effect. Here's the CSS co ...

Python Flask login screen not showing error message

Currently, I'm in the process of developing a login screen that incorporates Bootstrap and utilizes jQuery keyframes shaking effect. The backend functionality is managed by Flask. However, I seem to be encountering an issue where the error message "Wr ...

Angular - Javascript - Oops! The variable 'google' seems to have gone missing after reloading the page

For my website, I utilized Angular 2+ and integrated the Google Maps Api by adding the following code to my index.html file: <script async defer src="//maps.googleapis.com/maps/api/js?[myKey]&libraries=places"> </script> ...

Ion-content - Consisting of three elements with varying vertical positioning

I've been facing a challenge trying to include 3 different components (such as buttons, images, etc.) with distinct vertical alignment within the same ion-view. One should be aligned at the top, one in the middle, and one at the bottom. Take a look a ...

The disparities between CryptoJS in JavaScript and Mcrypt in PHP yield varying outcomes

When encrypting data using jscript (cryptoJS) and mcrypt in php, some unexpected results were observed. The IV key and keybase64 values differ between the two encryption methods. Take a look at the comparison below: JSCRIPT(cryptoJS) function crypto_encr ...

Displaying the selected item right at the center of the Flatlist in React Native

I need to ensure that the item selected in the FlatList is always centered. The chosen item should have a different style compared to the others. <FlatList data={items} style={styles.listStyle} ...

What is the method for retrieving the status of an xmlHttpRequest?

I'm curious about how to verify the status of an xmlHttp request once it has been sent. Can someone explain the process to me? Thank you. function sendRequest(){ //retrieve access token var accessToken = 'xxx'; //get user_id ...

Preventing the closure of a Nativescript Angular modal when tapping on the background

I'm relatively new to NativeScript and I'm trying to figure out how to prevent my custom modal from closing when the user taps on the background, specifically for Android devices. It's easy to achieve this with the dialogs provided by Nativ ...

Is it possible to utilize JavaScript to retrieve information from a database and organize it into a list format?

I've been working on a solution for this problem, but it's not quite working as expected. So far, I've managed to retrieve all the necessary data that requires ordering. What I'm looking for now is a way to sort all that information fr ...

How to efficiently deploy multiple Angular applications on a single VPS using nginx

I have two web applications initialized from https://github.com/Swiip/generator-gulp-angular. My goal is to deploy one application at and the other at . Below is the nginx configuration I am using for this purpose: location /app1 { proxy_pass http://m ...

Looking to iterate through MongoDB using a promise and a forEach loop? I'm aiming to populate an array

I've been struggling to iterate through elements in my MongoDB database and save the values to an array. Despite putting in hours of effort, I can't seem to get it done. Here's the code snippet: //shopController.js const Product = require ...