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

Tips for sending a PHP JSON array to a JavaScript function using the onclick event

I am trying to pass a PHP JSON array into a JavaScript function when an onclick event occurs. Here is the structure of the PHP array before being encoded as JSON: Array ( [group_id] => 307378872724184 [cir_id] => 221 ) After encoding the a ...

Can you provide tips on how to center the title on the page?

Currently, I am working on codepen.io and have been tasked with creating a paragraph that includes a title. However, my dilemma lies in the fact that I need this title to be center-aligned without directly altering the "x" value. Unfortunately, CSS is not ...

retrieving the element's height results in a value of 'undefined'

I am attempting to get the height of a specific element, but unfortunately I keep getting undefined. Here is what I have tried: var dl; $(window).load(function(){ dl = $("#dashboard_left").height(); }); $(document).ready(function(){ alert(dl); } ...

Warning: Potential Infinite Loop when using Vue JS Category Filter

I developed a program that filters events based on their program and type. The program is working correctly, however, an error message stating "You may have an infinite update loop in a component render function" keeps popping up. I suspect that the issue ...

Encountering an issue with a loop in my jQuery function - any solutions?

Having encountered an issue with a select object not working in my form-building function, I resorted to using an ajax call to fetch data from a database table. While the network tab in Chrome shows the data being retrieved successfully, the console displa ...

An object-c alternative to encodeURIComponent

Having difficulty finding information on this through a search engine. Is there a similar method in Objective-C for encoding URI components? http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp This is a common task, but I am unable to locate any ...

Loading Google Maps with Ajax

Exploring the world of google maps has been quite entertaining for me, however, I find myself in need of some assistance. The issue at hand involves a small block of HTML/Javascript that can be seamlessly integrated into a standard HTML page or loaded into ...

How can I display a Skeleton when pressing pagination buttons and then turn it off after 3 seconds?

Here is a snippet of my code featuring the use of a Skeleton as a placeholder for CardMedia: {loading ? ( <Skeleton variant="rectangular" width={308} height={420} animation="wave" /> ) : ( <CardMedia s ...

Adding a Stripe pay button using Jquery append results in the return of an [object HTMLScriptElement

I'm currently working on dynamically adding the Stripe pay with card button through jQuery. I've decided to append it because I only want it to show up once a specific condition is met by the user, as well as due to the fact that the pricing can ...

Utilize AJAX in JavaScript file

I am encountering an issue with the following code: function inicioConsultar(){ $(function(){ $('#serviciosU').change(function(){ if ($('#serviciosU').val()!= "-1") { $.ajax({ url: "@Url. ...

What are the steps for building an AngularJS application where all views are consolidated in a single file?

Is there a way to create an AngularJS app that is self-contained in one file, similar to jQuery Mobile's multi-page template? I'm looking to define multiple divs with ng-controller for different controllers and templates. However, angular-ui-rout ...

How can I update the datasource read URL and refresh the Kendo UI Grid with parameters?

I am working on a single page application using KendoUI and AngularJs. Within this application, I have two grids that are managed by two separate controllers. My goal is to pass the movieId of the selected row in the first grid to the second controller in ...

Can anyone help me troubleshoot this issue with uploading external JS scripts into my HTML code?

I'm currently facing an issue with my HTML document where the external js file is not loading. Here's a snippet of the HTML: <!DOCTYPE html> <html> <head> <title>...</title> <meta name="viewport" conten ...

`meteor.js and npm both rely on the fs module for file

I'm feeling a bit lost, as I need to use the fs package with Meteor.js framework. Starting from meteor version 0.6 onwards, I know that I should use Npm.require in the following way: var fs = Npm.require('fs'); However, when I try this, a ...

Utilizing Sequelize validation through condition objects

const db = require("../models"); const Meet = db.meet; checkDuplicateTime = (req, res, next) => { Meet.findAll({ where: { tanggal: req.body.date, waktu: req.body.time } }).then(time => { ...

Harnessing JavaScript templates within PHPHow to integrate JavaScript templates

I am currently working on a PHP document where I incorporate 'chapters' (jQuery tabs) in two different ways: Whenever a new chapter is generated, it gets added to the list as well as to the database using JavaScript and Ajax. I have already i ...

Getting the specific information you need from a JSON object in Angular 2

Struggling to extract specific data from a JSON file with nested objects like this: { "results" : [ { "address_components" : [ { "long_name" : "277", "short_name" : "277", "types" : [ "street_number" ] ...

What is the accurate user agent for Windows Phone?

Can someone explain why PHP and JavaScript produce different user agents? Which one is considered the accurate user agent? PHP User Agent Output: <?php print_r($_SERVER['HTTP_USER_AGENT']); ?> User Agent: Mozilla/5.0 (Mobile; Windows Ph ...

The functionality of AC_FL_RunContent is failing after an UpdatePanel postback

In the code for the repeater item, I have a JavaScript function that calls AC_FL_RunContent to display a flash file when a link within the repeater item is clicked. The datasource I am using displays the first page of video links with five items per page, ...

Loading images in advance using JavaScript

I have been searching through multiple forums and cannot seem to figure out the issue. The problem I am encountering is related to a website where there are three images with a hover effect. When the page first loads, there is a delay in loading the backgr ...