错误:[ng:areq]参数'customersCtrl'不是一个函数,未定义

时间:2018-11-16 08:03:18

标签: angularjs

我第一次使用angular.js,使用http请求动态呈现数据时,遇到了一个奇怪的问题,仅下面的代码就没有问题,但是如果将其放在我想做的页面中,会出现错误:

  

错误:[ng:areq]参数'customersCtrl'不是一个函数,未定义

但是我已经定义了customerCtrl

<div ng-controller="customersCtrl">

这是我的代码:

<div ng-app="myApp" >
<div ng-controller="customersCtrl">
    <script>
        var app = angular.module('myApp', []);
        app.controller('customersCtrl', function($scope, $http) {
            $http.get("http://localhost:17900/flower/flowers?flowerName")
                .then(function (result) {
                    $scope.names = result.data.body;
                });
        });
    </script>
</div>

2 个答案:

答案 0 :(得分:1)

您必须在<script>元素之外定义ng-app标记。如果您使用内联js,则必须在ng-app元素之前定义脚本标签。

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<script>
  var app = angular.module('myApp', []);
  app.controller('customersCtrl', function($scope, $http) {
    $scope.names = ["Aaran", "Aaren", "Aarez", "Aarman", "Aaron", "Aaron-James", "Aarron", "Aaryan", "Aaryn", "Aayan", "Aazaan", "Abaan", "Abbas"]

    // $http.get("http://localhost:17900/flower/flowers?flowerName")
    //   .then(function (result) {
    //   $scope.names = result.data.body;
    // });
  });
</script>

<div ng-app="myApp">
  <div ng-controller="customersCtrl">
    <p ng-repeat="name in names">{{name}}</p>
  </div>
</div>

注意

我建议您使用1.7.5

答案 1 :(得分:0)

问题是您在定义角度控制器之前将其包含在html标记中,因此角度编译器找不到customersCtrl作为函数。 像这样编辑您的代码:

<script>
        var app = angular.module('myApp', []);
        app.controller('customersCtrl',['$scope','$http' function($scope, $http) {
            $http.get("http://localhost:17900/flower/flowers?flowerName")
                .then(function (result) {
                    $scope.names = result.data.body;
                });
        }]);
 </script>
<div ng-app="myApp" >
<div ng-controller="customersCtrl"></div>