【问题标题】:AngularJS: '$scope is not defined'AngularJS:'$scope 未定义'
【发布时间】:2015-04-01 07:59:16
【问题描述】:

我不断收到 AngularJS 中此控制器代码的“$scope is not defined”控制台错误:

angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
        function($scope, $routeParams, $location, Authentication, Articles){
            $scope.authentication = Authentication;
        }
    ]);


$scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
    var article = new Articles({
        title: this.title,
        content: this.content
    });

    article.$save(function(response) {
        $location.path('articles/' + response._id);
    }, function(errorResponse) {
        $scope.error = errorResponse.data.message;
    });
};

我应该在 AngularJS MVC 文件中的哪个位置查找 $scope 定义不正确的问题?

【问题讨论】:

  • 是的,这是正确的错误。 $scope 是 injected 到您的控制器或任何因素或服务中,它在全球范围内不可用。你必须把它放在控制器或工厂中...... Angular 将匿名函数的 args 解析为字符串,然后分配值(如果已定义)。大约

标签: javascript angularjs mean-stack


【解决方案1】:

对于从 Google 登陆的其他人,如果您在为缩小功能添加注释时忘记了 $scope 周围的引号,则会收到此错误消息。

错误

app.controller('myCtrl', [$scope, function($scope) {
  ...
}]);

快乐的角度

app.controller('myCtrl', ['$scope', function($scope) {
  ...
}]);

【讨论】:

    【解决方案2】:

    只需将 $scope.create 函数放在控制器中即可。不在外面!

    $scope 只在控制器中定义,每个控制器都有自己的。所以在你的控制器之外写 $scope 是行不通的。

    【讨论】:

      【解决方案3】:

      将该代码放在控制器中:-

      angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
              function($scope, $routeParams, $location, Authentication, Articles){
                  $scope.authentication = Authentication;
      
      $scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
          var article = new Articles({
              title: this.title,
              content: this.content
          });
      
          article.$save(function(response) {
              $location.path('articles/' + response._id);
          }, function(errorResponse) {
              $scope.error = errorResponse.data.message;
          });
      };
              }
          ]);
      

      【讨论】:

      • 啊……我没有意识到我已经将“.create”方法放在了控制器函数之外。 (AngularJS的新手)感谢您的指导并指出问题!
      【解决方案4】:

      检查控制器定义后声明的范围变量。 例如:

          var app = angular.module('myApp','');
           app.controller('customersCtrl', function($scope, $http) {
           //define scope variable here.
      
      });
      

      检查视图页面中定义的控制器范围。

      例如:

      <div ng-controller="mycontroller">
      //scope variable used inside these blocks
      
      <div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-14
        • 2018-09-28
        • 1970-01-01
        • 1970-01-01
        • 2015-10-12
        • 1970-01-01
        • 2016-09-28
        • 1970-01-01
        相关资源
        最近更新 更多