Angular工作不正常?

时间:2016-08-07 17:45:58

标签: javascript angularjs

即使在正确的代码

之后,

angular js仍无法在我的浏览器中运行

我的代码 `

  <body ng-app>

  <div ng-controller="MainController">

    <h4>{{val}}</h4>

  </div>


<script>

var MainController = function($scope){
    $scope.val = "Testing angular";
};


</script>
`

我浏览器中显示的错误是: angular.js:13708 Error: [ng:areq] Argument 'MainController' is not a function, got undefined

3 个答案:

答案 0 :(得分:1)

您必须首先实例化模块

angular
  .module('app', [])
  .controller('MainController', MainController);

MainController.$inject = ['$scope'];

function MainController($scope){
    $scope.val = "Testing angular";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<body ng-app="app">
  <div ng-controller="MainController">
    <h4 ng-bind="val"></h4>
  </div>
</body>

答案 1 :(得分:0)

https://docs.angularjs.org/guide/migration#migrating-from-1-2-to-1-3

Angular停止从1.3开始寻找窗口对象上的控制器:

不起作用

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js"></script>
<body ng-app>

  <div ng-controller="MainController">

    <h4>{{val}}</h4>

  </div>


<script>

var MainController = function($scope){
    $scope.val = "Testing angular";
};


</script>

<强>使用:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular.min.js"></script>
<body ng-app>

  <div ng-controller="MainController">

    <h4>{{val}}</h4>

  </div>


<script>

var MainController = function($scope){
    $scope.val = "Testing angular";
};


</script>

答案 2 :(得分:0)

您需要告诉Angular它需要使用您正在创建的控制器。您可以使用以下方式明确告知它:

angular.module('module-name',[/*any dependencies*/]).controller('controller-name', controllerFunction)

以下是您可以嵌入并运行(JSBin)的示例:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body ng-app="TestApp">
  <div ng-controller="MainController">
    <h4>{{val}}</h4>
  </div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<script type="text/javascript">
  var MainController = function($scope){
    $scope.val = "Testing Angular";
  };

  angular.module("TestApp",[])
  .controller("MainController", MainController);

  </script>

</body>
</html>