Solving data within an Angular Controller

Recently delving into Angular development, I've found myself caught in a loop trying to solve this particular issue.

To give some context, I'm utilizing the MEAN stack through mean.io which includes Angular UI Router functionalities.

In my database, there is a Post model that can be associated with a category ID.

For new posts, I aim to fetch existing categories from the database and present them in a select box.

My understanding suggests that using resolve is necessary. However, it feels odd to embed logic within the resolve property located in a file named config.js. Currently, I've included the service call there and retrieved the categories using this code snippet:

.state('create post', {
    url: '/posts/create',
    templateUrl: 'views/posts/create.html',
    controller: 'PostsController',
    resolve: {
      loadCategories: function (Categories) {
        Categories.query(function(categories) {
            return categories;
        });
      }
    }
})

The initial hurdle is accessing the returned data in either my controller or view.

Additionally, I specifically want to retrieve categories tied to a particular Organization. Each user will have an organization ID, so how do I access the details of the currently signed-in user from within the config.js file? This location seems unfit for handling such complex logic.

I would greatly appreciate any assistance on this matter.

Thank you

Answer №1

This is the configuration file, config.js:

Defining the state for a post:

.state('post', {
        url: '/posts/create',
        templateUrl: 'views/posts/create.html',
        controller: 'PostsController',
        resolve: PostsController.resolve
      })

Registering the posts controller:

.controller({
     PostsController: ['$scope', 'loadCategories', PostsController],
     ...
    })

Function definition for the PostsController:

function PostsController($scope, loadCategories){
    $scope.categories = loadCategories;
};

PostsController.resolve = {
    loadCategories: ['dependencies', function(dependencies){
       return dependencies.query(...)
    }]
};

Angular handles dependency injection for you

Answer №2

If you have an angular resource called Categories, you can easily load it by using the following function:

loadCategories: function (Categories) {
    return Categories.query();
}

In your controller, you can then use this function as follows:

.controller('PostsController', function ($scope, loadCategories) {
     $scope.categories = loadCategories;
});

Based on your comments, it seems like you may encounter some challenges when trying to inject this into the controller only in specific states. One approach you could take is:

.state('create post', {
  url: '/posts/create',
  templateUrl: 'views/posts/create.html',
  controller: 'PostsController',
  data: {
    categories: Categories.query()
  }
})

Then in the controller:

.controller('PostsController', function ($scope, $state){
  console.log($state.current.data.categories);
});

This should resolve any issues you are facing...

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

What is the best way to decipher a base64 API response in AngularJs?

I'm currently facing a challenge where I have to decode the base64 encoded API response from the backend, instead of receiving it in JSON format. This is the response that I'm encountering: eyJzdGF0dXNDb2RlIjoiT0siLCJtZXNzYWdlIjoiU1VDQ0VTUyIsImR ...

Issue with fuse-box: unable to import ReactDOM

Recently, I decided to switch from webpack to fuse-box for my side project. Everything is compiling without any issues, but when I try to load it, an error pops up: I downloaded a React demo code and it works fine. Additionally, there are no problems wit ...

Encountering a type error while trying to create a document within a nested collection in Firebase Firestore

While trying to submit the form with property data, I encountered an error message: FirebaseError: Expected type 'za', but it was: a custom Ha object. There doesn't seem to be any information available online explaining what a Ha object is o ...

React compatibility problem with Internet Explorer 11

I'm encountering a problem with an error message stating "Expected identifier" in this code snippet. Any thoughts on what might be causing this issue? It seems like the problematic section of the code is originating from the transpiled version of th ...

Can you demonstrate how to incorporate a new line within a for loop?

I have an array of letters and I need to display them on the screen using a for loop. My goal is to make every sixth letter appear on a new line. Here is the code snippet: https://i.stack.imgur.com/lHFqq.jpg <script> export default { data() { ...

The Dynamic Duo: AngularJS and Thymeleaf

Has anyone tried combining Thymeleaf and AngularJS before? Which framework should take priority in rendering content? Suppose you have a Thymeleaf select element and would like AngularJS to populate it with a list of commands from a data source... < ...

Implementing the 'not-allowed' cursor style on disabled rows in Material UI datagrid

I have a specific disabled row in a Material UI data grid where users are unable to select or perform any actions on it. I am looking to display the cursor as "not-allowed" on this particular row. How can we apply styling to only this row since there is no ...

A guide to calculating the sum of columns using TypeScript and integrating it with Angular 8

Currently, I am attempting to calculate the average of all columns and display it at the footer of my table. The table data is fetched from an API resulting in a structure like this: <tr *ngFor="let item of items"> <td>{{item.num1 ...

Is it possible for the client to prevent the blocking of the Cross-Origin Resource Sharing (CORS) error?

I am encountering an issue with my web app that involves CORS operations when making $.getJSON AJAX calls. Typically, this functions properly on most client browsers due to the server having CORS enabled. However, I recently discovered that when using IE 1 ...

How can I display components using Angular CLI 5 without any visual output?

The index.html page is not displaying anything, not even the "App works" message that should appear in a basic initial project ng --version Angular CLI: 1.6.0 Node: 8.9.1 OS: darwin x64 Angular: 5.1.0 ... animations, common, compiler, compiler-cli, core, ...

Differences between async/await and then methods in React, demonstration shows that only async/await is functional. Why is

Trying to understand and implement two different API data fetching methods in React app development. The first method involves using the JavaScript Fetch API, while the second method utilizes the async/await syntax. I am currently experimenting with both a ...

Guide on implementing the 'cut' feature using electron-localshortcut

Looking for a way to use keyboard shortcuts on Mac without relying on the menu? I recently came across this helpful post: Is it possible to create non-global accelerators without adding them to a menu? Thanks to this informative article, I learned about ...

What exactly is HTML cloud storage all about?

As I work on developing an app through phonegap, one question that comes to mind is the possibility of storing information online. For instance, if there's a number variable that increases when a button is pressed, can this value be saved somewhere an ...

Exploring the isolated scopes of AngularJS directives

Exploring directives in AngularJS led me to this interesting code snippet: var app = angular.module('app', []); //custom directive creation app.directive("myDir", function () { return { restrict: "E", scope: { title: '@ ...

Stop event bubbling in Vue.js for router link

I'm working with the following HTML template... <template> <li class="nav-item" style="z-index:9"> <router-link :to="link.path" @click.native="linkClick" ...

The transfer of information through HTTP

I have been exploring the inner workings of HTTP servers and clients to better understand how data is transmitted. Despite reading numerous articles on the topic, I still have some lingering questions that remain unanswered. I would like to walk through th ...

Display the data count of a filtered list in Vue 2

As a newcomer to Vue, I am facing what seems like a simple and common task but the solution is escaping me. I need to filter some data and then display the count in a component. This is the HTML structure: <main class="container-fluid"> <div ...

Utilizing Node Js and Selenium webdriver, what is the process of dragging and dropping an element from its current position to a new position just below it?

After multiple attempts, I have come to realize that the following code is ineffective. driver.findElement(By.xpath(xpath)).then(function (element1) { driver.findElement(By.xpath(xpath)).then(function (element2) { ...

How do I implement an onClick event for an antd message component?

I have a question and I'm hoping for some help. Here is the code snippet in question: const [msgTimer, setMsgTimer] = useState(5); message.error('some error msg', msgTimer); In the antd documentation, the message component has an onClic ...

Customizing hyperlink styles with JavaScript on click

Hey there! I'm experimenting with something new. I've managed to change the background color of each link after it's clicked, but now I'm facing a challenge: How can I revert the original style when another link is clicked? Here's ...