Error ng areq

This is a long shot, but has anyone seen this error before? I am trying to add 'Transporters' using express, angular and mongoDB. I get this error whenever I access a page ruled by the transporters

This is a long shot, but has anyone seen this error before? I am trying to add ‘Transporters’ using express, angular and mongoDB. I get this error whenever I access a page ruled by the transporters controller:

Error: [ng:areq] http://errors.angularjs.org/1.2.12/ng/areq?p0=TransportersController&p1=not%20aNaNunction%2C%20got%20undefined
    at Error (native)
    at http://localhost:3000/lib/angular/angular.min.js:6:450
    at tb (http://localhost:3000/lib/angular/angular.min.js:18:360)
    at Pa (http://localhost:3000/lib/angular/angular.min.js:18:447)
    at http://localhost:3000/lib/angular/angular.min.js:62:17
    at http://localhost:3000/lib/angular/angular.min.js:49:43
    at q (http://localhost:3000/lib/angular/angular.min.js:7:386)
    at H (http://localhost:3000/lib/angular/angular.min.js:48:406)
    at f (http://localhost:3000/lib/angular/angular.min.js:42:399)
    at http://localhost:3000/lib/angular/angular.min.js:42:67 

The transporters controller looks like this:

'use strict';

angular.module('mean.transporters').controller('TransportersController', ['$scope', '$routeParams', '$location', 'Global', 'Transporters', function ($scope, $routeParams, $location, Global, Transporters) {
    $scope.global = Global;

    $scope.create = function() {
        var transporter = new Transporters({
            name: this.name,
            natl_id: this.natl_id,
            phone: this.phone
        });
        transporter.$save(function(response) {
            $location.path('transporters/' + response._id);
        });

        this.title = '';
        this.content = '';
    };

    $scope.remove = function(transporter) {
        if (transporter) {
            transporter.$remove();

            for (var i in $scope.transporters) {
                if ($scope.transporters[i] === transporter) {
                    $scope.transporters.splice(i, 1);
                }
            }
        }
        else {
            $scope.transporter.$remove();
            $location.path('transporters');
        }
    };

    $scope.update = function() {
        var transporter = $scope.transporter;
        if (!transporter.updated) {
            transporter.updated = [];
        }
        transporter.updated.push(new Date().getTime());

        transporter.$update(function() {
            $location.path('transporters/' + transporter._id);
        });
    };

    $scope.find = function() {
        Transporters.query(function(transporters) {
            $scope.transporters = transporters;
        });
    };

    $scope.findOne = function() {
        Transporters.get({
            transporterId: $routeParams.transporterId
        }, function(transporter) {
            $scope.transporter = transporter;
        });
    };
}]);

In my views I call the list and create methods. They generate the above error

I got this from the angular docs for ng:areq though still can’t figure what’s going on

AngularJS often asserts that certain values will be present and truthy
using a helper function. If the assertion fails, this error is thrown.
To fix this problem, make sure that the value the assertion expects is
defined and truthy.

Here’s the view that calls the controller public/views/transporters/list.html:

<section data-ng-controller="TransportersController" data-ng-init="find()">
    <ul class="transporters unstyled">
        <li data-ng-repeat="transporter in transporters">
            <span>{{transporter.created | date:'medium'}}</span> /
            <h2><a data-ng-href="#!/transporters/{{transporter._id}}">{{transporter.name}}</a></h2>
            <div>{{transporter.natl_id}}</div>
            <div>{{transporter.phone}}</div>
        </li>
    </ul>
    <h1 data-ng-hide="!transporters || transporters.length">No transporters yet. <br> Why don't you <a href="/#!/transporters/create">Create One</a>?</h1>
</section>

Transporters service code:

angular.module('transporterService', [])
    .factory('Transporter', ['$http', function($http){
        // all return promise objects
        return {
            get: function(){
                return $http.get('/api/transporters');
            },
            create: function(transporterData){
                return $http.post('/api/transporters', transporterData);
            },
            delete: function(id){
                return $http.delete('/api/transporters/'+id);
            }
        };
    }]);

Добрый день, angular выдает ошибку Error: [ng:areq] Argument ‘usersCtrl’ is not a function, got undefined .
Не могу понять почему он ругается, для теста написал самое простое взаимодействие и все вроде должно работать, но нет. В проекте есть так же контроллеры и они работают нормально, проблема в создании новых собственно скриншоты кусков кода.:

<script src="scripts/controllers/pageUserCtrl.js" type="text/javascript"></script>

controller
d0c18010a069475185c94ecfadce9525.png
app.js
b82b5f6cf2ab4e2289a16a3af9fbc379.png
user.html 43dde21a3bea4864a6a6124ff2a7ac8f.png
error 91315d3f04f44e72ba8e453a40f83386.png


  • Вопрос задан

    более трёх лет назад

  • 1751 просмотр

Пригласить эксперта

//app.js
angular.module('prApp', [])
    .controller('usersCtrl',['$scope' , function ($scope) {
        $scope.message = 'Page test';
    }
]);
//users2Ctrl.js
angular.module('prApp')
    .controller('users2Ctrl', UsersCtrl)
    
UsersCtrl.$inject = ['$scope'];

function UsersCtrl ($scope) {
  $scope.message = 'User2Ctrl';
}

или

//app.js
angular.module('prApp', [
  '..',
  'userCtrl'
]);

//userCtrl.js
angular.module('userCtrl', [])
.controller('userCtrl',...

Angular style guide на русском


  • Показать ещё
    Загружается…

12 февр. 2023, в 20:53

25000 руб./за проект

12 февр. 2023, в 20:15

10000 руб./за проект

12 февр. 2023, в 20:14

100000 руб./за проект

Минуточку внимания

User448619955 posted

I try to use AngularJS and ASP.NET MVC together. I use some pages such as masterpage.cshtml, changepassword and etc. in _layout I’ve used ngRoute to use my pages like SPA ,so far so good, here is my codes and scripts in masterpage.cshtml.

<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myApp">
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js"></script> <script type="text/javascript"> var angualarModule1 = angular.module('myApp', ['ngRoute']); angualarModule1.config(function ($routeProvider) { debugger; $routeProvider.when('/firstPage', { templateUrl: 'ManageUsers/changepassword', controller: 'ManageUsersController' }); }); </script>
...
... <div ng-view></div> ...
...

and in changepassword.cshtml page

@model BranchPanel.Models.ResetPasswordViewModel
@{
    Layout = null;
}

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script>
    angualarModule1.controller('myCtrl',
        function ($scope, $http, $location, $window) {
           
            //******=========Change Password=========******
            $scope.saveCustomer = function () {
                $scope.result = false;
                debugger;
                $http({
                    method: 'POST',
                    url: '/ManageUsers/ChangePassword',
                    data: $scope.custModel
                }).success(function (data, status, headers, config) {
                    debugger;
                    if (data[0] === "success") {

                        $scope.result = true;
                        $scope.status = data[0];
                        $scope.message = data[1];

                        console.log(data);
                    } else {
                        $scope.result = true;
                        $scope.status = data[0];
                        $scope.message = data[1];

                    }
                }).error(function (data, status, headers, config) {
                    $scope.message = 'Unexpected Error while saving data!!' + data.errors;

                    console.log($scope.message);
                });


            };
        });
</script>
<title>Change Pass</title>

<section class="content" >
   
    <div class="row" ng-controller="myCtrl">

            <div class="col-md-12">
                <div ng-include="'/Message.html'" ng-show="result">

                </div>
                <!-- USERS LIST -->
                <div class="box box-success">

                    <div class="box-body">

                        <div class="form-horizontal">
                   
                            <hr/>
                            @Html.ValidationSummary(true, "", new {@class = "text-danger"})

                            <div class="form-group">
                                @Html.LabelFor(model => model.CurrentPassword, htmlAttributes: new {@class = "control-label col-md-2"})
                                <div class="col-md-2">
                                    @Html.EditorFor(model => model.CurrentPassword, new {htmlAttributes = new {@class = "form-control", ng_model = "custModel.CurrentPassword"}})
                                    @Html.ValidationMessageFor(model => model.CurrentPassword, "", new {@class = "text-danger"})


                                </div>
                            </div>

                            <div class="form-group">
                                @Html.LabelFor(model => model.Password, htmlAttributes: new {@class = "control-label col-md-2"})
                                <div class="col-md-2">
                                    @Html.EditorFor(model => model.Password, new {htmlAttributes = new {@class = "form-control", id = "password", ng_model = "custModel.Password"}})
                                    @Html.ValidationMessageFor(model => model.Password, "", new {@class = "text-danger"})


                                </div>
                            </div>

                            <div class="form-group">
                                @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new {@class = "control-label col-md-2"})
                                <div class="col-md-2">
                                    @Html.EditorFor(model => model.ConfirmPassword, new {htmlAttributes = new {@class = "form-control", ng_model = "custModel.ConfirmPassword"}})
                                    @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new {@class = "text-danger"})


                                </div>
                            </div>

                        </div>
                    </div>
                    <hr/>
                    <div class="box-footer">
                        <div class="form-group">
                            <div class="col-md-12">
                                <input type="submit" id="ChangePass" value="change" class="btn btn-success col-md-1 text-left" ng-click="saveCustomer()"/>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
    </div>
</section>
@*}*@




after clicking on my button saveCustomer
function must be run ,but it does not.in console watch I get an error as bellow:

angular.js:9997 Error: [ng:areq] http://errors.angularjs.org/1.2.20/ng/areq?p0=ManageUsersController&p1=not%20a%20function%2C%20got%20undefined
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js:6:450
at Bb (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js:19:68)
at Ua (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js:19:155)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js:67:405
at link (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js:7:248)
at K (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js:54:390)
at f (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js:47:261)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js:46:377
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js:48:217
at w (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js:52:47) <div ng-view="" class="ng-scope">

I shared an error that I got stuck for several hours.

Error message

Error: [ng:areq] http://errors.angularjs.org/1.3.10/ng/areq?p0=userRequestController&p1=not%20aNaNunction%2C%20got%20undefined

error code

The above error occurred when I customized an angular route. The previous code is as follows:

.state('userRequestController', {
    url: "/ossapp/zk/synchronized.html",
    templateUrl: "views/request/userRequest.html",
    params: {reqUrl: null, backUrl: null},
    data: {pageTitle: 'Sync Switch'},
    controller: "userRequestController",
    resolve: {
        deps: ['$ocLazyLoad', function ($ocLazyLoad) {
            return $ocLazyLoad.load([{
                insertBefore: '#ng_load_plugins_before',
                files: [
                    'js/scripts/modules/request/userRequestController.js'
                ]
            }]);
        }]
    }
})

Official misinterpretation

Check the angularjs error message document (Document address), the error message given is as follows:

DESCRIPTION

AngularJS often asserts that certain values will be present and truthy using a helper function. If the assertion fails, this error is thrown. To fix this problem, make sure that the value the assertion expects is defined and truthy.

translate to Chinese:

description

AngularJS usually asserts that certain values ​​will appear to ensure that the referenced function is useful. To solve this problem, make sure that the value of the assertion is correctly defined and referenced.

Troubleshooting stage:

  1. Check that the referenced controller and html template address are correct
  2. Check the name of the viewing page and the controller reference is correct
  3. Ensure that all dependencies used have no reference errors
  4. 。。。
    The error is found here, the text on the page has been able to be displayed correctly, butError: [ng:areq]It still exists. Although it does not affect the page, the error is still very dazzling in the console (if it was a warning at the time, I might not care).

After that, I checked the referenced controller, and the reference was correct, but when I commented out the code referenced to the controller in the route, the error disappeared. Suddenly understand

If the controller is referenced in the route and the controller is not used in the page, angularjs will check this kind of reference to assert that it is an invalid reference and throw aError: [ng:areq]mistake.

In other words, if the controller is not used in the page for a while, don’t reference it in the route. Comment out in the routecontroller: “userRequestController”Can

Solved this inexplicable bug, I really feel sour and refreshed, continue to code~~

END

This is my demo using angularjs, for creating a service file, and adding service to a controller.

I have two problems with my demo:

  • One is when I put <script src="HomeController.js"> before <script src="MyService.js"> I get this error,

Error: [ng:areq] Argument ‘HomeController’ is not a function, got undefined

  • The other is when I put <script src="MyService.js"> before <script src="HomeController.js"> I get the following error,

Error: [$injector:unpr] Unknown provider: MyServiceProvider <- MyService

My source:

File Index.html:

<!DOCTYPE html>
<html >
    <head lang="en">…</head>
    <body ng-app="myApp">
        …
        <div ng-controller="HomeController">
            <div ng-repeat="item in hello">{{item.id + item.name}}</div>
        </div>

        <script src="Scripts/angular.js"></script>
        <script src="Scripts/angular-route.js"></script>

        <!-- App libs -->
        <script src="app/app.js"></script>    
        <script src="app/services/MyService.js"></script>
        <script src="app/controllers/HomeController.js"></script>
    </body>
</html>

File HomeController.js:

(function(angular){
    'use strict';

    var myApp = angular.module('myApp',[]);

    myApp.controller('HomeController',function($scope,MyService){    
        $scope.hello=[];
        $scope.hello = MyService.getHello();
    });
})(window.angular);

File MyService.js:

(function(angular){
    'use strict';

    var myApp = angular.module('myApp',[]);

    myApp.service('MyService', function () {
        var hello =[  {id:1,name:'cuong'},
            {id:2,name:'nguyen'}];
        this.getHello = function(){
            return hello;
        };
    });

})(window.angular);

25 Answers

This creates a new module/app:

var myApp = angular.module('myApp',[]);

While this accesses an already created module (notice the omission of the second argument):

var myApp = angular.module('myApp');

Since you use the first approach on both scripts you are basically overriding the module you previously created.

On the second script being loaded, use var myApp = angular.module('myApp');.

I experienced this error once. My problem was that I wasn’t adding the FILE_NAME_WHERE_IS_MY_FUNCTION.js

so my file.html never found where my function was

Once I add the «file.js» I resolved the problem

<html ng-app='myApp'>
    <body ng-controller='TextController'>
    ....
    ....
    ....
    <script src="../file.js"></script>
    </body>
</html>

Also ensure that your controllers are defined within script tags toward the bottom of your index.html just before the closing tag for body.

 <!-- build:js({.tmp,app}) scripts/scripts.js -->
    <script src="scripts/app.js"></script>
    <script src="scripts/controllers/main.js"></script>
    <script src="scripts/controllers/Administration.js"></script>
    <script src="scripts/controllers/Leaderboard.js"></script>
    <script src="scripts/controllers/Login.js"></script>
    <script src="scripts/controllers/registration.js"></script>

provided everything is spelled «correctly» (the same) on your specific.html, specific.js and app.js pages this should resolve your issue.

Happened to me few times whenever I miss «,» between list of injections and function

app.controller('commonCtrl', ['$scope', '$filter',function($scope,$filter) {

}]);

I also experienced this error but in my case it was because of controller naming convention. I declared controller: "QuestionController" in .state but in controller definition I declared it like

yiiExamApp.controller('questionController' ...

but it should be

yiiExamApp.controller('QuestionController' ...

hope that helps to people facing this error because of this stupid mistake I wasted 4hour in identifying it.

If ALL ELSE fails and your running locally on the MEAN stack like me with gulp…just stop and serve again! I was pulling my hear out meticulously checking everything from all of your posts to no avail till I simply re-ran gulp serve.

I got the same error. I defined java script like this

<script src="controllers/home.js" />

then I changed to the this

<script src="controllers/home.js"></script>

After this my problem is solved.

I also encountered this same error and the fix for me was to include my child module in the main module array.

var myApp = angular.module('myApp', ['ngRoute', 'childModuleName']);

I had similar issue. The fix was ensure that your ctrollers are not only defined within script tags toward the bottom of your index.html just before the closing tag for body but ALSO validating that they are in order of how your folder is structured.

<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<script src="scripts/controllers/Administration.js"></script>
<script src="scripts/controllers/Leaderboard.js"></script>
<script src="scripts/controllers/Login.js"></script>
<script src="scripts/controllers/registration.js"></script>

I also encountered this problem in my project. It eventually worked after I inserted the my-controller.js into my karma.conf.js file, with the <script> tag.

Hope this will help. There are quite many reasons that can lead to this problem.

I also got this error.

I had to add my new controller to routing information.
srcjsapp.js

angular.module('Lillan', [
  'ngRoute',
  'mobile-angular-ui',
  'Lillan.controllers.Main'
])

I added my controller to make it look like

angular.module('Lillan', [
  'ngRoute',
  'mobile-angular-ui',
  'Lillan.controllers.Main',
  'Lillan.controllers.Growth'
])

Cheers!

Obviously that previous posts are useful, but any of above are not helpful in my case. The reason was in wrong sequence of loading scripts. For example, in my case, controller editCtrl.js depends on (uses) ui-bootstrap-tpls.js, so it should be loaded first.
This caused an error:

<script src="scripts/app/station/editCtrl.js"></script>
<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>

This is right, works:

<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>
<script src="scripts/app/station/editCtrl.js"></script>

So, to fix the error you need first declare all scripts without dependencies, and then scripts that depends on previously declared.

Try this

    <title>My First Angular App</title>

</head>

<body>

     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

    <h3>Adding Simple Controller<h3>        

    <div ng-controller="SimpleController">
        Name:

        <br/>

        <input type = "text" data-ng-model = "name"/> {{name}}

        <br/>

        <ul>    
            <li data-ng-repeat = "cust in customers | filter:name | orderBy:'city'">
                {{cust.name}} - {{cust.city}}
            </li>
        </ul>

    </div>


    <script>

        var angularApp = angular.module('angularApp',[]);

        angularApp.controller('SimpleController', [ '$scope', SimpleController]);

        function SimpleController($scope)
        {

            $scope.customers = [
                                    {name:'Nikhil Mahirrao', city:'Pune'},
                                    {name:'Kapil Mahire', city:'Pune'},
                                    {name:'Narendra Mahirrao', city:'Phophare'},
                                    {name:'Mithun More', city:'Shahada'}

                                ]; 
        }

    </script>

</body>

In my case, I was missing the name of the Angular application in the html file. For example, I had included this file to be start of my application code. I had assumed it was being ran, but it wasn’t.

app.module.js

(function () {
    'use strict';

    angular
        .module('app', [
        // Other dependencies here...
        ])
    ;

})();

However, when I declared the app in the html I had this:

index.html

<html lang="en" ng-app>

But to reference the Angular application by the name I used, I had to use:

index.html (Fixed)

<html lang="en" ng-app="app">

I was getting the error because i had added the controller script before the script where i had defined the corresponding module in the app.
First add the script

<script src = "(path of module.js file)"></script>

Then only add

<script src = "(path of controller.js file)"></script>

In the main file.

Error: ng:areq Bad Argument has gotten me a couple times because I close the square bracket too soon. In the BAD example below it is closed incorrectly after ‘$state’ when it should actually go before the final parenthese.

BAD:

sampleApp.controller('sampleApp', ['$scope', '$state'], function($scope, $state){

});

GOOD:

sampleApp.controller('sampleApp', ['$scope', '$state', function($scope, $state){

}]);

Yes. As many have previously pointed out,
I have added the src path to all the controller files in the index.html.

<script src="controllers/home.js"></script>
<script src="controllers/detail.js"></script>
<script src="controllers/login.js"></script>
<script src="controllers/navbar.js"></script>
<script src="controllers/signup.js"></script>

This fixed that error.

I had the same problem, but I forgot to include the file into grunt/gulp minimization process.

grunt.initConfig({
  uglify: {
    my_target: {
      files: {
        'dest/output.min.js': ['src/input1.js', 'src/missing_controller.js']
      }
    }
  }
});

Hope that helps.

In my situation this error appeared when I didn’t declare function within an array argument.

The one with error:

taskAppControllers.controller('MainMenuCtrl', []);

The fixed one:

taskAppControllers.controller('MainMenuCtrl', [function(){

}]);

Also check for spelling mistakes.

var MyApp = angular.module('AppName',[]);
MyApp.controller('WRONG_SPELLING_MyCtrl', ['$scope', MyControllerCtrl])
function MyControllerCtrl($scope) {
   var vm = $scope;
   vm.Apple = 'Android';
}

<div ng-controller="ACTUAL_SPELLING_MyCtrl">
    {{Apple}}
</div>

Check if your HTML page includes:

  1. angular.min script
  2. app.js
  3. controller JavaScript page

The order the files are included is important. It was my solution to this problem.

Hope this helps.

sampleApp.controller('sampleApp', ['$scope', '$state', function($scope, $state){

Same thing for me, comma ‘,’ before function helped me in fixing the issue — Error: ng:areq Bad Argument

My controller file was cached as empty. Clearing the cache fixed it for me.

I accidentally moved my HomeController.js out of the directly, where it was expected.
Putting it again on original location.

After that my website started to load pages automatically every second, I was even unable to look at the error. So i cleared the browser cache. It solved the problem

For me the solution was to add a semicolon after one of the functions declared in my HomeController.js

//Corrected code is :
app.controller('HomeController', function($scope, $http, $log) {

  $scope.demo1 = function(){
      console.log("In demo");
  } //Here i forgot to add the semicolon
  
  $scope.demo2 = function(){
      console.log("In demo");
  };
  
});

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error frame alliancedialog already encountered
  • Error found while importing rig in this animation file unity
  • Error found when loading home user profile
  • Error found option without preceding group in config file mysql
  • Error forwarding the new session empty pool of vm for setup capabilities

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии