angularjs ng-controller不起作用

时间:2015-06-04 16:31:56

标签: javascript angularjs

我正在尝试使用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}}被&#39; 3&#39;正确替换,但{{name}}不是。我期待&#39; toto&#39;。

我也试图在点击事件上显示提醒,但它不起作用:

<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>

当我点击时,没有任何反应。

2 个答案:

答案 0 :(得分:4)

尝试:<body ng-app> ==&gt; <body ng-app="MyApp">

在你的剧本中:

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

答案 1 :(得分:3)

别忘了

  • 声明您的角度应用angular.module('MyApp', [])
  • 在您的正文<body ng-app="MyApp">
  • 中插入正确的属性
  • 不要忘记括号ng-click="onMyButtonClick()

试试这个

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

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

        $scope.onMyButtonClick = function(){
            alert("test");
        }
    }])
&#13;
<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>
&#13;
&#13;
&#13;