【问题标题】:(angularjs) getting 'ReferenceError: $scope is not defined' when injecting controller(angularjs)在注入控制器时得到'ReferenceError:$scope未定义'
【发布时间】:2014-09-11 13:51:30
【问题描述】:

我正在努力学习 AngularJS。我有一个 HTML 页面,我试图在其中注入模块但出现错误

主js文件:

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

classificationModule.controller('firstcontroll',function(){
    $scope.text="Goodday"
});

HTML页面:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta name="layout" content="main"/>
    <title>Classification Toolkit for Grails</title>          

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js"></script>
    <asset:javascript src="main.js"/>        

</head>
<body >   
    <div ng-app='mainapp' ng-controller='firstcontroll'>
        Hello, {{text}}
    </div>   

</body>
</html>

得到以下错误:

ReferenceError: $scope is not defined

我不知道我做错了什么。

【问题讨论】:

  • 将@scope 替换为$scope。 @ 不是有效的 javascript 令牌
  • 做到了。出现新错误。是不是我laoding angular JS的方式有问题?

标签: javascript html angularjs


【解决方案1】:

尝试在函数中传递$scope。

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

classificationModule.controller('firstcontroll', function($scope) {
  $scope.text = "Goodday"
});
<!DOCTYPE html>
<html>

<head lang="en">
  <meta charset="UTF-8">
  <meta name="layout" content="main" />
  <title>Classification Toolkit for Grails</title>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.js"></script>
  <asset:javascript src="main.js" />

</head>

<body>
  <div ng-app='mainapp' ng-controller='firstcontroll'>
    Hello, {{text}}
  </div>

</body>

</html>

【讨论】:

    【解决方案2】:

    你应该写

    var classificationModule = angular.module('mainapp', []);
    
    classificationModule.controller('firstcontroll', function($scope) {
      $scope.text = "Goodday"
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app='mainapp' ng-controller='firstcontroll'>
      Hello, {{text}}
    </div>

    $scope 是 Angular JS 的依赖注入系统提供的一个变量,基本上它是通过将提供者与命名参数匹配来工作的。

    【讨论】:

    • 谢谢。我现在明白了
    猜你喜欢
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多