2015-02-07 31 views
-1

這是我第一次嘗試使用Angular。我試圖從Internet上運行現有的代碼,並給出了錯誤:錯誤:錯誤:定義控制器時,areq Bad Argument

Error: error:areq Bad Argument 
Argument 'ngAddressListController' is not a function, got undefined 

此代碼的工作以及與AngularJS < 1.3,但它在1.3+

代碼給問題如下HTML

<!doctype html> 
<html ng-app=""> 
<head> 
    <title>Ng Addressbook</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script> 
    <script src="main.js"> </script> 
</head> 
<body> 
<div ng-controller="ngAddressListController"> 
    <h3>Ng Address Book</h3> 
    <div id="container"> 
     <h3>There are 4{{contacts}} Contacts So far</h3> 
     <ul> 
      <li> 
       <span>First Name</span> 
       <span>Last Name</span> 
      </li> 
     </ul> 
    </div> 

</div> 
</body> 
</html> 

main.js

function ngAddressListController($scope) 
{ 
    $scope.contacts = [ 
     {first_name:'Jane', last_name:'Doe'}, 
     {first_name:'Jhon', last_name:'Doe'} 
    ]; 
} 

似乎有棱角< 1.3是,我應該堅持嗎?

+0

哪裏是爲調用此功能的控制器JS?即'app.controller('MyCtrl',ngAddressListController);' – haxtbh 2015-02-07 17:29:18

+0

@haxtbh你能詳細說明嗎? – Volatil3 2015-02-07 17:31:36

+1

請參閱https://docs.angularjs.org/api/ng/directive/ngController - 在示例app.js中設置控制器,然後在其下面定義該函數。你有這樣的事嗎? – haxtbh 2015-02-07 17:33:47

回答

1

我並不確定地知道,但是鑑於用於定義控制器的方法(帶有全局函數)在AngularJS文檔中直到1.2.19,然後在1.2.20中消失,我會認爲這種做法已被廢棄。

傳統的方式來定義一個控制器如下:

// define an app module 
angular.module('myApp', []) 
// add a controller to it 
.controller('ngAddressListController', ['$scope', function ($scope) { 
    $scope.contacts = [ 
     {first_name:'Jane', last_name:'Doe'}, 
     {first_name:'Jhon', last_name:'Doe'} 
    ]; 
}]); 

然後在你的HTML,你可以使用你的應用程序的名稱:

<html ng-app="myApp"> 

這種風格是在合適的使用從版本1.2.20開始的ngController文檔的頂部。

https://docs.angularjs.org/guide/controller

另見本說明在1.2.19文檔:

NOTE: Although Angular allows you to create Controller functions in the global scope, this is not recommended. In a real application you should use the .controller method of your Angular Module for your application as follows

+0

'錯誤:錯誤:modulerr 模塊錯誤 無法實例化模塊myApp,原因如下: 錯誤:[$ injector:nomod] http://errors.angularjs.org/1.3.1/$injector/nomod?p0=myApp at error(native)' – Volatil3 2015-02-07 17:38:09

+0

@ Volatil3對不起,應該是'angular.module',而不是'angular.app'。它的工作原理是 – JLRishe 2015-02-07 17:40:07

+0

。謝謝。但是,我有點懷疑我應該使用1.3.x還是堅持使用1.2.x,因爲我第一次使用它? – Volatil3 2015-02-07 17:42:03