Angular Strict Di is forgiving and does not raise an error if a controller employs implicit annotation inside a Directive

I encountered a problem with my minified AngularJS 1.x application

Uncaught Error: [$injector:unpr] Unknown provider: nProvider <- n

After following suggestions from similar questions, I implemented strict dependency injection during the bootstrap process of our application like this

angular.bootstrap(document, [app.name], {
        strictDi: true
    });

Even though I added this, I did not face any issues when running the application with non-minified code. However, when I minified the code, I started getting the unknown provider error. According to the AngularJS documentation, it should throw an error if there is any implicit annotation while using strict dependency injection. But for some reason, it was not happening.

I eventually discovered that the problem was in one of the directives which had a controller with an implicit annotation for $scope, as shown below

angular.module('MyModule', [])
.directive('myTabs', function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: {},
    controller: function MyTabsController($scope) {
      var panes = $scope.panes = [];

      $scope.select = function(pane) {
        angular.forEach(panes, function(pane) {
          pane.selected = false;
        });
        pane.selected = true;
      };

      this.addPane = function(pane) {
        if (panes.length === 0) {
          $scope.select(pane);
        }
        panes.push(pane);
      };
    },
    templateUrl: 'my-tabs.html'
  };
})

The issue was resolved after implementing Inline Array Annotation.

I am curious why strict DI did not throw any errors. Do I need to make any other changes to my code?"

Answer №1

After extensive experimentation, I successfully developed an angular application that utilizes strict dependency injection through both manual and automatic bootstrap methods.

Links to the Plunkers can be found below:

Manual Bootstrap: https://plnkr.co/edit/9QoKpzzjvFHMT1ZdTIoy?p=preview

Automatic Bootstrap: https://plnkr.co/edit/kBXOpY?p=preview

My findings revealed that if the controller lacks explicit annotation for dependencies, Angular throws an error during bootstrap, citing:

angular.js:12798 Error: [$injector:strictdi] ScrollDirectiveController is not using explicit annotation and cannot be invoked in strict mode
http://errors.angularjs.org/1.4.12/$injector/strictdi?p0=ScrollDirectiveController
    at angular.js:68
    at Function.annotate [as $$annotate] (angular.js:3825)
    at Object.invoke (angular.js:4548)
    at extend.instance (angular.js:9435)
    at nodeLinkFn (angular.js:8540)
    at compositeLinkFn (angular.js:7975)
    at nodeLinkFn (angular.js:8571)
    at compositeLinkFn (angular.js:7975)
    at compositeLinkFn (angular.js:7978)
    at publicLinkFn (angular.js:7855)

The problem stemmed from our usage of Inline Array Annotation in defining the controller without specifying any dependencies, as demonstrated by the code snippet:

function scrollDirective($window) {
  return {
    restrict: 'A',
    scope: {
      callback: '&scrollDirective'
    },
    link: function(scope, element, attrs) {
         //some code here
    },
    controller: [function ScrollDirectiveController($scope) {
      console.log("controller loaded!!");
    }]
  };

To address this issue, I've also prepared a Plunker showcasing the correct implementation: https://plnkr.co/edit/nkzvmeoeV9ARHVMzWHFI?p=preview

Remarkably, Angular encountered no errors in this revised scenario.

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

Ways to access a JavaScript function on a div with multiple identifiers

Currently working on developing a discussion panel using ASP.net, where each comment is assigned a unique id. I am looking to trigger the jQuery click function whenever a user clicks on a comment. However, since the comment ids are dynamically assigned an ...

How can I make the URL dynamically update when loading views into a layout using ajax in CakePHP?

function loadContent(source){        $.ajax({              type: "post",  // Method: post              url: source, // Source URL              success: function(response) {                    ...

Using mongoose's create() method may result in unexpected modifications to your documents

Currently engaged in a MEAN-based project, I am integrating the MongoDB and Node.js components with AngularJS. I am utilizing Mongoose for schemas, which has proven to be quite convenient. However, I am encountering unexpected behavior with nested schemas. ...

Setting up Laravel Mix Vue.js source maps to display actual component code during debugging

My current setup includes Laravel 5.4 and Vue.js 2.6. I'm facing an issue with viewing the sourceMap of *.vue component files in the console. Here is how I've configured Laravel mix: let mix = require('laravel-mix'); mix.webpackConfig ...

Invoker of middleware and stack functions for Express.js with a focus on capturing the response object

It appears that the expressjs app contains a stack of Layer object Arrays. What function is utilized to pass the I am curious about: When a request is sent from the http client, which function is called first and how are the stack array functions with mi ...

What is the reason for using a wrapper with fs.readFile when a callback is included as an argument?

Recently delving into Node.js, I encountered a perplexing scenario while using fs.readFile(). Initially, my attempt to read a file led me to use: fs.readFile("file.txt",function(err,data) { if(err) {throw err;} console.log(data); }); However, to ...

PHP function with JSON response encountered an error during the AJAX call

I am currently working on creating a News Ticker that utilizes PHP, Javascript, and AJAX. The first step involved creating a PHP function called getFeed(), which gathers data from various news websites into an Array. This data is then returned in JSON form ...

Grab the div, position it accurately, and initiate an ajax call

So many tasks on my plate, but let's prioritize. Within a <div class="showcase">, I have numerous <div class="game"> elements, each with an onclick="addpop('delpopup.php?id=something&pos=somethingelse&box=image')" Does ...

Guide to positioning a rectangular shape within a QML Pane

When working with this code, focus on the pink box outlined in blue and the blue box inside it. https://i.sstatic.net/NH8YS.png I'm looking to position the blue Rectangle to the right of the pink box. How can this be achieved? Why are the anchors no ...

In Javascript, you can compare an array with a nested array and then store the values in a new array

Two arrays are at hand const arrayOne = [ {id: '110'}, {id: '202'}, {id: '259'} ]; const arrayTwo = [ {data: [{value: 'Alpha', id: '001'}]}, {data: [{value: 'Bravo', id: '202'}]}, ...

Tips for sending arguments up in Angular2

I need to supply an argument to a function. <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> It's crucial for me, as I have ...

Navigating Error: net::ERR_CONNECTION while utilizing Puppeteer

I attempted to utilize a proxy from the following site: Below is my Puppeteer scraping code (deployed on Heroku), encountering an error at the .goto() method, as mentioned in the title: const preparePageForTests = async (page) => { const userAgent = & ...

The type 'Observable<Response>' does not include a property called 'map'

I recently started learning angular and npm, but encountered an error while trying to replicate some code from a source I found (linked here). It seems like the error is related to my development environment, but I'm having trouble pinpointing the ex ...

Click on the email link to access the AngularJs application

Seeking advice from those who have experience with similar applications. I am currently developing an online testing app. For instance, HR professionals can create test sessions for job applicants and send them a link to access the app. Upon clicking the ...

Utilizing media queries to tailor the pre-designed website and ensure adaptability

I find myself in a situation where I need to make adjustments to my current website to ensure it fits properly on smaller desktop screens. While the site is viewable on all screen sizes, issues arise with screens as small as 14 inches, resulting in an unwa ...

Leveraging the power of promises to handle multiple requests

Recently, I encountered an issue while trying to use the request-promise module to check multiple websites simultaneously. When using Promise.all as intended, the promise would return with the first rejection. I sought a better way to execute multiple requ ...

Vue.js versatile form for both adding and editing

As a newcomer to the world of vue.js, I am currently working on expanding some tutorials that I have completed. After struggling with this for three hours now, I must admit that I am feeling quite frustrated. Just to give you a heads up, I am using firebas ...

When using Mongoose's save function within an async.each loop, it may

While working on an array processing task that involves saving and validating data asynchronously, I encountered an issue with duplicates. Here is the data I'm currently processing: var guests = [{ "email": "<a href="/cdn-cgi/l/email-protection" ...

Putting Text Inside a Video Player in HTML

Is there a way to insert text, like a Logo, into my video player? https://i.sstatic.net/CZ6Rp.png I would appreciate any help on how to achieve this. Thank you. <video width="320" height="240" controls src="video/flashtrailer.mp4"> Your browser ...

Utilize local JSON file to display images on a webpage using AngularJS

Where am I making a mistake? I am trying to display images from a datahl.json file on my web page, but for some reason, I am unable to access them. Please review the code snippets below and help me out. If possible, provide a solution using Plunker edito ...