无法访问AngularJs控制器内的代码

时间:2017-11-04 16:09:57

标签: javascript html angularjs

我很确定我错过了一些非常愚蠢的东西,但由于某些原因我的控制器内的代码没有被读取。

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="libraries/angular/angular.min.js"></script>
    <script src="libraries/jquery/jquery-3.2.1.min.js"></script>
    <script src="app/app.js"></script>
    <script src="app/controllers/mainCtrl.js"></script>
    <!--<meta charset="UTF-8">-->
</head>
<body>
<div ng-app="app1"></div>

</body>
</html>

app.js

angular.module('app1', []);

mainCtrl.js

console.log('out'); // Working
angular.module('app1').controller('mainCtrl', ['$scope', '$http', function($scope, $http){
    console.log('in'); // Not working
}]);

4 个答案:

答案 0 :(得分:2)

您需要指定要使用的控制器..

<body ng-app="app1"><div ng-controller="mainCtrl"></div></body>

答案 1 :(得分:1)

<!DOCTYPE html>
<html lang="en"> 
<head> 
<script src="libraries/angular/angular.min.js"></script>
 <script src="libraries/jquery/jquery-3.2.1.min.js"></script>
 <script src="app/app.js"></script>
 <script src="app/controllers/mainCtrl.js"></script> 
<!--<meta charset="UTF-8">--> 
</head> 
<body> 
<div ng-app="app1" ng-controller="mainCtrl"></div> 
</body> 
</html>

答案 2 :(得分:0)

只需将您的&#39; ng-app&#39;并根据需要指定as many controllers,如下所示: -

 <body  ng-app="app1">
    <div class="main" ng-controller="mainCtrl">
        <p>Stuff here</p>
    </div>

    <div class="def" ng-controller="defController">
        <p>Other stuff here</p>
    </div>
    </body>

答案 3 :(得分:0)

简单。创建控制器。

       <div ng-app="app1">

       <div ng-controller="mainCtrl">
       <p>
       First Name
        <input type="text" ng-model="firstName" />
       </p>
       <p>
        Last Name:
        <input type="text" ng-model="lastName" />
        </p>
        <p>
        Full Name: 
        {{firstName}} {{lastName}}
        </p>
       </div>
       </div>

脚本:

 angular.module('app1', []);

 console.log('out'); // Working
 angular.module('app1').controller('mainCtrl', ['$scope', '$http', 
 function($scope, $http){
 alert('in'); // Not working

 $scope.firstName = "John";
 $scope.lastName = "Doe";
 }]);

检查:http://jsfiddle.net/dq8r196v/511/