2015-03-13 73 views
2

我習慣用Java對包含對象範例和MVC模式的許多文件進行編碼。如何在Angularjs中的其他文件中使用控制器

而我從AngularJS開始,我試圖啓用一個簡單的index.html誰在javascript文件中使用控制器,但不起作用。

我的html文件:index.html的

<html ng-app="carre"> 
<head> 
    <script src="js/angular.js"></script> 
    <script src="js/CalculCtrl.js"></script> 
    <script> 
     var ctrl = angular.module('carre',[]); 
    </script> 
</head> 
<body ng-controller="CalculCtrl"> 
    <div>{{2+2}}</div> 
    <p>{{temps}}</p> 
</body></html> 

我的JavaScript文件位於JS控制器/ CalculCtrl.js

carre.controller('CalculCtrl', function($scope) 
     { 
      $scope.temps = 'pluie'; 
      } 
) 

什麼是錯在這裏嗎? 在此先感謝。

+0

大家好,感謝您的答覆,但我已經嘗試了3個解決方案,並沒有一個工作... :( – 2015-03-13 15:46:22

回答

1

重命名carre.controller(...),以ctrl.controller

Ctrl爲變量保存到你的模塊的引用的名稱,卡雷是你賦予它在NG-應用參考名稱指示。

編輯:此外,我建議您獲取Chrome的Batarang擴展程序,它會向開發人員工具添加一個頁面以用於調試Angular應用程序。非常有用的工具。

1

你應該反轉文件包含與模塊聲明:

<html ng-app="carre"> 
<head> 
    <script src="js/angular.js"></script> 
    <script> 
     var carre = angular.module('carre',[]); 
    </script> 
    <script src="js/CalculCtrl.js"></script> 

</head> 

此外,因爲您使用的是被稱爲carreCalculCtrl.js變量,你應該在創建一個模塊時,從ctrlcarre重命名variabile的assignd :

var carre = angular.module('carre',[]); 
0

您已經創建模塊Ctrl鍵並用卡雷指it.And腳本序列wrong.The正確答案是

的index.html

<html> 
enter code here<html ng-app="carre"> 
<head> 
    <script src="js/angular.js"></script> 

    <script> 
     var carre = angular.module('carre',[]); 
    </script> 
    <script src="js/CalculCtrl.js"></script> 
</head> 
<body ng-controller="CalculCtrl"> 
    <div>{{2+2}}</div> 
    <p>{{temps}}</p> 
</body></html> 

CalculCtrl.js

carre.controller('CalculCtrl', function($scope) 
     { 
      $scope.temps = 'pluie'; 
     } 
); 
0

作爲替代其他的答案,你可以在它自己的模塊創建你CalculCtrl然後宣佈家樂福,當取決於該模塊上。

angular.module('Calcul', []) 
.controller('CalculCtrl', function($scope) 
    { 
     $scope.temps = 'pluie'; 
    } 
); 

,然後家樂福

angular.module('carre', ['Calcul']); 

這樣就不需要重新整理腳本標記,因爲它們是

0

答案是here

指數。 html

<html ng-app="AppliName"> 
    <head> 
    <--! we load angularjs --> 
     <script src="js/angular.js"></script> 
    <--! we load our controller in an other javascript file --> 
     <script src="js/mesControllers.js"></script> 
    </head> 

    <body ng-controller="myCtrl"> 
     <p>time is : {{temps}} </p> 
    </body> 
</html> 

位於js/mesControllers的mesControllers.js。JS

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

AppliName.controller('myCtrl', function ($scope) { 
    $scope.temps = 'pluie'; 
}); 

運行,並保持冷靜,現在的工作,P

相關問題