Maximus Decimus Maximus Decimus - 2 months ago 10
AngularJS Question

Angular injection error when adding the controller in a form of navbar dropdown

I'm very new to angularjs and SPA.

I was trying to use the navbar structure of bootstrap adding a login section as a dropdown in a index spa. I want to click on the sign in button and call the function to authenticate and hide the dropdown of login when the authentication is ok.

At the beginning I didn't include the controller in the HTML, but then I included the attribute ng-controller and I don't know why I'm getting this error

Error: [$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20MyService


So if I remove the ng-controller="MyController" I don't get the error but I cannot call the method from the controller and I tried this before but without any success.

angular.element(document.getElementById('frmMyController')).scope().authenticate();


But as I said if add the ngcontroller my app will generate the injection error.

I pasted my code in jsfiddle but it doesn't generate any error.

So, how can I call the method authenticate with the button sign in correctly and then if the response is ok, how to hide the dropdown button signin and show the profile authenticated?

Answer

It seems to be an injection error. Try to inject the $scope like this :

app.controller('MyController', ['$scope', 'MyService',function($scope, MyService){
    $scope.authenticate = function(username, password){
        MyService.authenticate(username, password);
    }
}])

You have to do it for all your components (config, service, etc).

I don't know which build system you are using, but if you are using gulp, you can add gulp-annotate to your build stream. It will add the injection's array automatically.

Edit 1

Remove the $scope from your service.

Comments