Invoking a service within the controller of the $stateprovider

I currently have my service being executed in my AppCtrl function, although this approach is not ideal. The service should only be needed when the user navigates to page2. How can I trigger my service specifically when the page2 state is active? I attempted using resolve but encountered difficulties in making it work correctly.

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


        $urlRouterProvider.otherwise('home');

        $stateProvider.state('home', {
          url: '/home',
          templateUrl: 'home.html'
        })

        $stateProvider.state('page2', {
          url: '/page2/:topicId',
          templateUrl: 'page2.html'
        // Where do I call my service here?
    });

    });

app.controller('AppCtrl', ['$scope', 'getTopicContent', function($scope,getTopicContent){
    getTopicContent.request().success(function(data){
        $scope.myList = data;
    });
}]);


app.factory('getTopicContent', ['$http', function($http){

    var query = function() {
        return $http({
            url: "http://www.corsproxy.com/mydata.me/level1/list.php",
            method: "GET"
        })
    }

    return {
        request : function(){
            return query();
        }

    }
}]);

Answer №1

One way to enhance your page is by creating a controller and injecting a service into it.

$stateProvider.state('page2', {
      url: '/page2/:topicId',
      templateUrl: 'page2.html',
      controller: 'Page2Ctrl'
});

Your controller can be structured as follows:

app.controller('Page2Ctrl', ['$scope', 'getTopicContent', function($scope,getTopicContent){
    getTopicContent.request().success(function(data){
        $scope.myList = data;
    });
}]);

If you want to utilize resolve, consider the following example:

$stateProvider.state('page2', {
      url: '/page2/:topicId',
      templateUrl: 'page2.html',
      controller: 'Page2Ctrl',
      resolve: {
          content: getTopicContent.request().success(function(data){
                      return $scope.myList = data;
                   });
      }
});

In your Page2Ctrl, you can then access and verify this content:

app.controller('Page2Ctrl', ['$scope', 'getTopicContent', function($scope, content){
    if (content) {
        $scope.content = content;
    }    
}]);

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

Delayed Page Update: Click Event Doesn't Execute Correctly Without JQuery

I'm a beginner in JavaScript and unable to use JQuery I have a table and I want to highlight the selected row on the click event. At the same time, I need to change the value of an input field. However, when I click on a row, the highlight effect get ...

Problem with jQuery's .prepend method being called twice on list items

Looking to enhance the appearance of a list by adding some icons before the anchor links within each list item. <ul class="submenu-children"> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> ...

JavaScript utilized to create a fully immersive full-screen webpage

I have been trying to implement a code for creating a full-screen website that works on all browsers. Unfortunately, my current code only seems to be functioning properly on Mozilla browser. When I try to view the site in Chrome and make it full screen, it ...

Validation of input in React using the onChange event handler

When trying to validate a numeric input using onChange in React, I encountered an issue where the input clears and React throws a ReferenceError: value is not defined. This error makes sense since there is nothing to validate when the input is empty. I ca ...

Mistakes encountered when compiling TypeScript Definition Files

I am looking to convert my JavaScript files (*.js) to TypeScript files (*.ts) in my ASP.net MVC5 application (not an Asp.net Core app). I am using Visual Studio 2015. After downloading the TypeScript Definition Files into the Scripts\typings\ fol ...

execution won't be halted by return statement within forEach in JavaScript

const checkAttendanceStudent = (attendance, std_id) => { //check if the teacher made attendance for this current session let checkNow = attendance.find((element) => { if (checkDateAttendance(element.date)) { //check if the s ...

Issue with ui-sref when using special characters in parameters

Take a look at my code snippet <a ui-sref="exeprofile({pname:@event})"></a> When I include the '@' symbol in the parameter, I encounter the following error message 'Error: [$parse:lexerr] Lexer Error: Unexpected next charac ...

Transforming a pair of lists into JSON format

I'm currently working on converting two lists into JSON format. Let's take a look at an example: list1 = ['a','b','a'] list2 = ['q','r','s'] The conversion should result in: [{ " ...

How come the pop-up isn't displaying in the middle of the screen?

I have encountered a positioning issue while using a semantic modal with Angular. The problem arises when I try to display the modal as it does not appear in the correct position. https://i.sstatic.net/o033E.png Below is the code snippet from my HTML fil ...

Some Node methods are absent in MongoDB

I'm a newcomer to Mongo and I've been facing some difficulties with the basics. The code provided below reveals that db.getCollectionNames is returning as undefined, along with db.foo.find() and db.foos.find() both causing errors even though the ...

JavaScript locate and change

I created a tool that generates code for my team. It's a simple process - just fill out the fields and it automatically replaces content in the DIV below, displaying the updated code. It's pretty convenient! The only issue I'm facing is th ...

Issue: friends.js file contains an unexpected token "<" error after implementing express.static and modifying HTML content upon button click

On localhost:9000, I'm attempting to load home.html initially. However, when I try it with my current code, I encounter the error: friends.js:1 Uncaught SyntaxError: Unexpected token <. I'm unsure about the meaning of this error. Additionally, ...

`Vue.js child component not reflecting updated prop value`

Created a functionality within the App.vue parent component to communicate with all child components, instructing them to close any open modals. Additionally, implemented a feature for a child component to notify the parent to hide the overlay when the mai ...

Utilizing the reduce() function to simultaneously assign values to two variables from data input

Looking to simplify the following function using reduce(), as the operations for variables selectedEnrolled and selectedNotEnrolled are quite similar. I attempted to use map(), but since I wasn't returning anything, it led to unintended side effects ...

Tips for implementing a repeater item to function beyond the ng-repeat directive

Recently, I decided to play around with AngularJS and now I seem to be facing a small issue with ng-class. Specifically, I'm attempting to change the color of an awesome font icon. <div ng-controller="MyCtrl"> <i ng-class="{'test': ...

Please elaborate on the appropriate application of angularjs Directives in this specific scenario

From my experience with Angular, I've learned that directives are used for manipulating the DOM while controllers are more about controlling functionality. I've been struggling to convert a small wizard into generic directives, aiming for reusab ...

Saving canvas generated images using the toDataURL() method in IE 11 triggers a "Security Error" message

I'm currently developing a browser-based tool for media distributors that involves manipulating video content. Within this tool, I have an HTML5 video player that loads videos from an external domain (e.g. ). The domain specifies the following header ...

Guide on syncing Bootstrap 4 sliders using a single set of controls

Is it possible to synchronize a bootstrap 4 carousel with controls to a carousel without any controls? 1) When the control arrows are clicked, both carousels will slide simultaneously. 2) Hovering over either carousel will pause both carousels from slidi ...

"Error encountered: Unable to locate Google API while attempting to load page using ajax

My website includes a Google Maps API, and it works perfectly fine. However, when I attempt to load the page using jQuery Ajax, the script stops working. <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script t ...

Enhancing packet verification through analysis of improbability of fraudsters?

I am currently developing a whiteboard application that utilizes canvas, allowing everyone in the room to view and draw on the board. Essentially, whenever one person draws something, a packet is sent to the server and then broadcasted to all other partici ...