为什么ng-click没有触发此按钮?

时间:2017-01-05 22:01:36

标签: angularjs

ng-click按钮无效。

有没有人发现以下代码段有什么问题?



var locationModel = {
  "City": "Alexandria",
  "State": "State"
};

var locationApp = angular.module("locationApp", []);

locationApp.controller("locationCtrl", function($scope) {
  $scope.newLocation = locationModel;

  $scope.addLocation = function(state) {
    console.log(state);
    //$http.post("/Home/CreateLocation", newLocation).then(function (response) {
    //    console.log("Inserted", data);
    //});
  }
});

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

<body ng-controller="locationCtrl">
  <div>

    <button class="btn btn-default" ng-click="addLocation('VA')">
      Add
    </button>

  </div>
</body>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

你的html中需要ng-app

&#13;
&#13;
var locationModel = {
        "City": "Alexandria",
        "State": "State"
    };

    var locationApp = angular.module("locationApp", []);

    locationApp.controller("locationCtrl", function ($scope) {
        $scope.newLocation = locationModel;

        $scope.addLocation = function (state) {
            console.log(state);
            //$http.post("/Home/CreateLocation", newLocation).then(function (response) {
            //    console.log("Inserted", data);
            //});
        }
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="locationApp" ng-controller="locationCtrl">
<div> 

    <button class="btn btn-default" ng-click="addLocation('VA')">
        Add
    </button>

</div>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您需要添加ng-app指令,以便您的应用运行,将body标记更新为以下内容:

<body ng-controller="locationCtrl" ng-app="locationApp">

答案 2 :(得分:0)

是的 - 我忘记了ng-app标签。我打算把它放在html标签中。 它现在正在运作。