简体   繁体   中英

AngularJS button ng-click not working

index.html

 <!DOCTYPE html>
<html ng-app="todoApp">
<head>
  <title>To Do List</title>
  <link href="skeleton.css" rel="stylesheet"/>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="todoController">
  <div class="section hero">
    <div class="container">
      <div class="row">
        <div class="three columns">
            <li>
              <button class="button button-primary" ng-click="btnClick(first)">Data 1</button>
            </li>
        </div>
        <div class="nine columns">
          <h4>{{dataText}}</h4>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

app.js

var app = angular.module('todoApp', []);
app.controller('todoController', function ($scope) {
      $scope.dataText = "";
      $scope.btnClick = function (num){
        dataText = "This is data from the " + num + " button."
      };
  });

When I click the button, I would expect the ng-click to initiate and call the function in the controller, but when I click nothing happens, the text on the screen doesn't change or anything. What am I doing wrong?

There is no variable named first in your html,

 <li>
   <button class="button button-primary" ng-click="btnClick(first)">Data 1</button>
 </li>

Instead of that, Pass it as a string

 <li>
   <button class="button button-primary" ng-click="btnClick('first')>Data 1</button>
 </li>

Also change the line like this,

  $scope.btnClick = function (num){
    $scope.dataText = "This is data from the " + num + " button."
  };

Here is the working Plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM