2015-06-04 118 views
1

我正在嘗試使用AngularJS,而我的「ng-controller」不起作用。angularjs ng-controller不起作用

<!DOCTYPE html> 
    <html> 
    <head> 
     <script type="text/javascript" src="lib/angular.js"></script> 
    </head> 
    <body ng-app> 
     <h1>Add user</h1> 
     <form action="addUser" method="post"> 
     <input type="text" name="pseudo" placeholder="pseudo"> 
     <input type="password" name="password" placeholder="password"> 
     <input type="submit" value="envoyer"> 
     </form> 
     {{1 + 2}} 
     <div ng-controller="myController"> 
     {{ name }} 
    </div> 
    <a href="./remove">supression</a> 
    <script type="text/javascript"> 
     function myController($scope){ 
     alert("test"); 
     $scope.name = 'toto'; 
     } 
    </script> 
    </body> 
</html> 

當我想這在Chrome,{{1+2}}正確的 '3' 所取代,但{{name}}不是。我預計'toto'。

我也想上顯示點擊事件的警報,這是行不通的:

<script type="text/javascript"> 
    var myApp = angular.module('MyApp', []); 
    myApp.controller('myController', ["$scope",function($scope){ 
    $scope.name = 'toto'; 
    $scope.onMyButtonClick = function(){ 
     alert("test"); 
    } 
    }]) 
</script> 

HTML

<div ng-controller="myController"> 
    {{ name }} 
    <button ng-click="onMyButtonClick">test</button> 
</div> 

當我點擊,什麼也不會發生。

+0

角度的功能,必須創建渲染體前。在你的頭標上添加腳本 –

+0

這也行不通:/ – Raph

回答

4

嘗試:<body ng-app> ==><body ng-app="MyApp">

在你的腳本:

angular.module('MyApp', []) 
.controller('myController', ["$scope",function($scope){ 
    $scope.name = "toto" 
}]) 
+0

這是工作! :D非常感謝你!!!!!! :d – Raph

3

不要忘記

  • 聲明你的角度應用angular.module('MyApp', [])
  • 插入正確的屬性在你的身體<body ng-app="MyApp">
  • 不要忘記括號ng-click="onMyButtonClick()

試試這個

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

 
    myApp.controller('myController', ["$scope",function($scope){ 
 
     $scope.name = 'toto'; 
 

 
     $scope.onMyButtonClick = function(){ 
 
      alert("test"); 
 
     } 
 
    }])
<body ng-app="MyApp"> 
 
<h1>Add user</h1> 
 
<form action="addUser" method="post"> 
 
    <input type="text" name="pseudo" placeholder="pseudo"> 
 
    <input type="password" name="password" placeholder="password"> 
 
    <input type="submit" value="envoyer"> 
 
</form> 
 
{{1 + 2}} 
 

 
<div ng-controller="myController"> 
 
     {{ name }} 
 
     <button ng-click="onMyButtonClick()">test</button> 
 
    </div> 
 
<a href="./remove">supression</a> 
 

 
</body> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>