(angularjs)在注入控制器时获取'ReferenceError:$ scope未定义'

时间:2014-09-11 13:51:30

标签: javascript html angularjs

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

主js文件:

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

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

HTML PAGE:

<!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

我不知道我做错了什么。

2 个答案:

答案 0 :(得分:3)

尝试在函数中传递$scope

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

classificationModule.controller('firstcontroll', function($scope) {
  $scope.text = "Goodday"
});
&#13;
<!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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你应该写

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

classificationModule.controller('firstcontroll', function($scope) {
  $scope.text = "Goodday"
});
&#13;
<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>
&#13;
&#13;
&#13;

$ scope是由角度JS&#39;提供的变量。依赖注入系统,基本上它通过匹配提供者到命名参数来工作。