Resolving AngularJS routes while invoking a controller with ng-include

Feel free to check out my Plunkr demonstration by clicking here.

In my application's app.js file, I've defined two controllers along with a route provider that includes a resolve function for the TestController.

var app = angular.module('app', ['ngRoute']);
 
app.controller('DefaultController', ['$scope', function($scope){
  $scope.welcome = "Hello World";  
}]);
 
app.controller('TestController', ['$scope', 'context', '$routeParams', function($scope, context, $routeParams){
  $scope.text = "TestController loaded!"  
}]);
 
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider){
  $routeProvider.
    when('/test1',{
      templateUrl: 'test1.html',
      controller: 'TestController',
      resolve: {
        context: function(){return 'test';}
      }
    })
}])

Within my HTML code, I utilize an ng-include directive to load test.html in the default view alongside the TestController.

 <body ng-controller="DefaultController">
    <h1>{{welcome}}</h1>
 
    <div ng-include="'test.html'" ng-controller='TestController'></div>
 
    
  </body>

I'm trying to figure out if it's possible to resolve the contextProvider directly from the ng-include or if there are better alternative approaches to achieve this. Any guidance on this matter would be highly appreciated.

Answer №1

To streamline your code, consider creating a factory or service:

app.factory('dataResolver', function() {
    return {
        resolveData: function() {
            return 'example';
        }
    }
});

Next, integrate this into your router setup:

app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider){
  $routeProvider.
    when('/example',{
      templateUrl: 'example.html',
      controller: 'ExampleController',
      resolve: {
        context: function(dataResolver) {
             return dataResolver.resolveData();
        }
      }
    })
}])

Apply the same approach in your controller:

app.controller('ExampleController', ['$scope', 'dataResolver', '$routeParams', function($scope, dataResolver, $routeParams){
  $scope.text = "ExampleController loaded!"
  var context = dataResolver.resolveData();
}]);

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

Error: The React component throws a TypeError because it is unable to read the property 'map' from an undefined source

I encountered the following error TypeError: Cannot read property 'map' of undefined at ListItemFactory.ts:84:57 at The specific line where the error occurs is: return announcementitems=json.value.map((v,i)=>( To provide mor ...

The protractor-jasmine2-html-reporter fails to generate an HTML report

In my protractor config.js, I have set up the configuration to generate screenshots in a specific folder, but the HTML report is not being generated. I have followed the steps mentioned in this guide: https://www.npmjs.com/package/protractor-jasmine2-htm ...

Tips for setting up a cleanup function in useEffect when making API calls within a context provider

Looking to showcase a list of products categorized and fetched from an API? Check out the code snippet below: const API = "https://dummyjson.com/products"; const ProductsList = () => { const { cate } = useParams(); //retrieving category fro ...

Getting AJAX query parameters from a JavaScript data object: A step-by-step guide

When utilizing jQuery to make an AJAX request, you have the option to define the data property that will be sent to the server. If the data consists of an array of objects, it will be transmitted to the server in a format similar to this: MyArray[0][MyPro ...

utilizing angularjs and bootstrap to manage multiple button models

Recently delved into learning angularjs and bootstrap. Found a tutorial on creating buttons. <div ng-controller="ButtonsCtrl"> <h4>Checkbox</h4> <pre>{{checkModel}}</pre> <div> <button type="butto ...

What is the solution for the error message "Unhandled Runtime Error" with the description "TypeError: videoRef.current.play is not a function"?

I am currently working on implementing custom controls for a video on a Nextjs website. When using a standard HTML <video> component, the code functions as expected and clicking the custom play button successfully plays the video. However, when I swi ...

NodeJS: Encountering an issue with retrieving the cart ID - receiving

I am having issues with the cart variable, even though I defined it using await cartsRepo.create({ items: [] });. For some reason, I keep getting undefined when trying to access cart. I suspect that the request is not resolving properly, which might be ca ...

The value of Component.name is not consistent during the BUILD process in NextJS

I have multiple pages with different layouts. To switch between layouts, I am currently using the Component.name in _app.js. While this approach works during development, after building and starting the project with npm start, it seems like the Component.n ...

Session storage conditional statement is not behaving as anticipated in JavaScript

I am currently working on session storage functionality where a user must select one radio button on the first page and then click the next button. On the second page, a div is supposed to show up. On the first page, I have created a function with a set of ...

Extract data from JSON using the parse function

After utilizing the function JSON.stringify(), I have obtained this JSON: {"get":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'== ...

Tips for retaining the selected radio button in a Java web application even after a page refresh

As someone new to web development using the Stripes Framework, I am encountering an issue with radio buttons on a webpage. When one of the radio buttons is selected, a text box and Submit Button appear. After clicking the Submit button, the functionality ...

The YUI framework is skilled at creating new lines while erasing the old ones

I am looking to create a line when the mouse is clicked, and remove the previously drawn line. View the code on jsfiddle.net at this link. While my current code successfully draws a line when the mouse is clicked, it does not remove the previous line. I n ...

Tips for preparing data prior to downloading it as a CSV file

Trying to export data as a CSV file, encountering an issue with the generated file content: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[ ...

Preventing unauthorized access to files in ExpressJS public directories

Is there a way to conceal files served by the Node server? Despite my attempts to redirect certain files and directories, Express 4.X does not seem to cooperate. I have also experimented with sending 4XX HTTP responses when specific files are requested, bu ...

What is the best way to simulate a worker for testing in Jest?

Currently facing a test challenge: import { convertHeicToPng } from './heicUtils'; class Employee { url: string; onmessage: (m?: any) => void; constructor(stringUrl: string) { this.url = stringUrl; this.onmessage = () => {}; ...

Encountering the error message "The function $(...).tablesorter is not defined" while using webpack

After updating to Rails 6 with Webpack, I'm encountering the error message Uncaught TypeError: $(...).tablesorter is not a function. Below is the snippet of my environment.js file: const { environment } = require('@rails/webpacker') const w ...

Transform various tables enclosed in separate div elements into sortable and filterable tables

I'm encountering an issue with making multiple tables sortable and searchable on one page. Despite all the tables having the same class and ID, only the first table is responsive to sorting and searching. I've followed a tutorial that recommends ...

Dealing with a Node and Express server can be tricky, especially when trying to proxy a POST request along with parameters. You might encounter the error

I am trying to forward all requests made to /api/ from my local node server to a remote server, while also adding some authentication parameters to them. Everything works smoothly for GET requests with query parameters and POST requests without specifying ...

delivering several requests using Promises

I have experimented with encapsulating two query responses within an object and then using that object as the return value in a function app.get('/gerais',(req,res) => { const client = new Client(); const data = new Object(); clie ...

Error: Attempting to access the 'clipboard' property on an undefined object results in a TypeError when invoking this.$q.electron.clipboard

I'm currently working on incorporating copy to clipboard functionality into my app using Electron. This is the command I am using: methods: { copyToClipboard () { if (process.env.MODE === 'electron') { this.$q.electro ...