Unable to distribute item produced by factory

When attempting to share an object array posts.shoppingCart through controllers, there appears to be a discrepancy between how it works in MainCtrl compared to AuthCtrl. While the expression

$scope.cart = posts.shoppingCart;
functions correctly in MainCtrl, it does not work in AuthCtrl. The dummy data, however, displays without any issues.

var app = angular.module('test', ['ui.router']);

app.config(['$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {

        $stateProvider.state('home', {
            url : '/home',
            templateUrl : '/home.html',
            controller : 'MainCtrl',
            resolve : {
                postPromise : ['posts',
                    function(posts) {
                        return posts.getAll();
                    }]

            }
        }).state('login', {
            url : '/login',
            templateUrl : '/login.html',
            controller : 'AuthCtrl',
            onEnter : ['$state', 'auth',
                function($state, auth) {
                    if (auth.isLoggedIn()) {
                        $state.go('home');
                    }
                }]

        }).state('register', {
            url : '/register',
            templateUrl : '/register.html',
            controller : 'AuthCtrl',
            resolve : {
                postPromise : ['posts',
                    function(posts) {
                        return posts.getShoppingCart();
                    }]

            },
            onEnter : ['$state', 'auth',
                function($state, auth) {
                    if (!auth.isLoggedIn()) {
                        $state.go('login');
                    }
                }]

        });

        $urlRouterProvider.otherwise('login');
    }]);


app.factory('posts', ['$http', 'auth',
    function($http, auth) {
        var o = {
            posts : [],
            shoppingCart : []
        };

        o.getAll = function() {
            return $http.get('/catalog').success(function(data) {
                angular.copy(data, o.posts);
            });
        };

        o.getShoppingCart =  function() {
            return o.shoppingCart;
        };

        return o;
    }]);



app.controller('MainCtrl', ['$scope', 'posts','auth',
    function($scope, posts, auth) {

        $scope.posts = posts.posts;
        $scope.isLoggedIn = auth.isLoggedIn;
        //setting title to blank here to prevent empty posts

        $scope.sum = 0;
        if ($scope.sum === 0) {
            $scope.isDisabled = true;
        }

        $scope.cart = posts.shoppingCart;
        var sum;
        $scope.addPost = function(post) {
            console.log(post);
            $scope.cart.push({title: post.title, cost: post.cost});
            var sum = parseInt($scope.sum,10) + parseInt(post.cost, 10);

            $scope.sum = sum;
            $scope.isDisabled = false;
        };
    }]);

app.controller('AuthCtrl', ['$scope', '$state', 'posts', 'auth',
    function($scope, posts, $state, auth) {
        $scope.user = {};
        $scope.isLoggedIn = auth.isLoggedIn;
        $scope.cart = [
            {title:'Jani',cost:'Norway'},
            {title:'Hege',cost:'Sweden'},
            {title:'Kai',cost:'Denmark'}
        ];//posts.shoppingCart;

        $scope.register = function() {
            console.log($scope.user);
            auth.register($scope.user).error(function(error) {
                $scope.error = error;
            }).then(function() {
                $state.go('home');
            });
        };

        $scope.logIn = function() {

            auth.logIn($scope.user).error(function(error) {
                $scope.error = error;
            }).then(function() {
                $state.go('home');
            });
        };
    }]);

Answer №1

['$stateParams', '$location', 'articles', 'authentication',
function($stateParams, articles, $location, authentication) {

There seems to be a mix-up between $location and articles...

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

Console log showing no response from AJAX request

For my group project, I've been working on setting up an API to display a response in the console log. After troubleshooting and fixing errors, I am still not seeing any response when I click submit. JavaScript var zipcode = ""; function localMovie ...

Using ng-repeat in conjunction with ui-router conditions

Utilizing ui router ($routeprovider and $locationprovider) for angular js, I am looking to adjust the array being looped through in an ng-repeat based on the current url/route. Despite browsing similar threads on stack, I have not found a precise solution ...

Utilizing both a named function and an arrow function as event handlers in React

Can you spot the issue in the code snippet below? export default function App() { const [count, setCount] = useState(0); return ( <div className="App"> <h2>{count}</h2> <button onClick={() => { ...

Ensuring the functionality of WebAPI endpoints through JavaScript

Is there a foolproof way to ensure that your WebAPI controller routes stay aligned with the client-side requirements? Let's say you have a BooksController for your WebAPI. On the client side, a method is invoked by calling the endpoint like this: $. ...

JavaScript Newbies Encounter OnFocus Dilemma

How can I add default grey text to a text field on an ASP.net page, and make it disappear when the user clicks or enters the field? I have successfully implemented onFocus event for changing text color in my .aspx page using a <script> tag with JS c ...

Unselect all checkboxes except for the one that was clicked

In a project, I have 3 checkboxes that are interconnected and when one is clicked or checked, I want the others to be cleared while keeping the clicked checkbox checked. This behavior is similar to radio buttons but I cannot use radio buttons due to client ...

Is there a way to identify a keydown or keypress event in angular.js?

Seeking guidance on how to fetch the value from a mobile number textbox for validation using angular.js. As a beginner in working with angular.js, I am uncertain about implementing events and incorporating JavaScript to validate or manipulate form inputs w ...

When echoing JSON data into a page used as a same-origin iframe, the outcome is not as anticipated

I am facing an issue with Javascript and PHP. Here is the setup I have: <html> <body> <iframe id="a" src="iframe.php" width="500" height="200"></iframe> </body> </html> Within ifr ...

When attempting to print a Rectangle on my webpage using JavaScript and taking user input, I encountered an error stating that 'str' is not defined

I'm trying to implement a feature where clicking on the "try it" button will prompt the user for the number of lines and then print that many lines in the form of a rectangle. However, when I run my code, nothing appears on the DOM and there is an err ...

Performing a Search Operation using AJAX with Elasticsearch

I've been struggling to find the correct method for requesting data from elasticsearch using a jQuery AJAX call. I keep encountering parsing errors or getting all documents in the index instead of my intended results. $(document).ready(function() ...

Can the website be inaccessible to human users in any way?

In my PHP programming journey, I encountered a challenge that I need help with. I created a function to retrieve data via ajax in my PHP code, but realized that users can manipulate the site by manually entering the ajax request link or altering its valu ...

Scanning the header of panel groups for information

I'm currently working on developing a custom search engine to navigate through the panel-group that I've created, but I seem to be struggling with selecting the correct elements. The structure of my generated Markup is as follows: <div id="o ...

Guide on setting up Facebook Ads for IOS with React Native

I'm encountering an issue in React Native while attempting to launch my app on IOS, where a warning message is displayed: "Module AdChoiceManager requires main queue setup since it overrides 'init' but doesn't implement 'requiresM ...

How can I validate HTML input elements within a DIV (a visible wizard step) situated within a FORM?

I recently made a decision to develop a wizard form using HTML 5 (specifically ASP.NET MVC). Below is the structure of my HTML form: @using (Html.BeginForm()) { <div class="wizard-step"> <input type="text" name="firstname" placeholder ...

Access your account using Google authentication within an Angular framework

My latest project involves creating an API that allows users to log in with Google by using the endpoint http://localhost:3001/api/v1/user/google. Here's how it works: A user clicks on the link http://localhost:3001/api/v1/user/google The endpoint h ...

Using the on-change event with a textfield can help ensure that the field is cleared if the min-date condition is not met

I recently encountered an issue with an input field that had the type "datetime" and a min-date condition set to today's date. The flow was such that if a valid date was entered, the submit button would be enabled, otherwise it would remain disabled. ...

Innovative JavaScript function

Seeking a solution for my JavaScript function that should only be executed when the browser screen width exceeds 1024px. if ($(window).width() > 1024) { An issue arises when a user initially loads the webpage on an 800px browser screen and then resize ...

Angular encountered an issue with an HTTP POST request, as the 'Access-Control-Allow-Origin' header was not found on the requested resource

I have been attempting to transmit data to a servlet using Angular HTTP POST requests. var httpPostData = function (postparameters, postData){ var headers = { 'Access-Control-Allow-Origin' : '*', &a ...

How can I retrieve the $index value of an ng-repeat element within a uib-dropdown?

I am currently working on implementing an ng-repeat loop that includes a dropdown menu for each element. I want the dropdown menu to contain functions that operate on the specific element, requiring access to the index of that element. Below is the code sn ...

The current status of the Macrotask and Microtask queues as this calculation is being processed

This particular inquiry delves into a nuanced aspect of the event loop, seeking clarification through a concrete example. While it shares similar characteristics with another question on Stack Overflow, specifically Difference between microtask and macrota ...