簡體   English   中英

angularjs ng-controller不起作用

[英]angularjs ng-controller doesn't work

我正在嘗試使用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>

當我點擊時,沒有任何反應。

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

在你的腳本中:

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

別忘了

  • 聲明你的角度應用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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM