单击按钮后AngularJS输出文本框值

时间:2019-06-02 07:09:20

标签: javascript html angularjs

我在angularjs中有一个简单的形式,它输入值a和值b。当我单击按钮时,我希望值被警告。我该怎么办?

<div ng-controller="myController">
    <p><label>value a : </label><input type="text" ng-model="valuea" name="valuea" id="valuea" /></p>
    <p><label>value b  : </label><input name="valueb" id="valueb" ng-model="valueb"/></p>

    <button type="button" ng-click = "add()"  >Sign In</button> 
</div>

<script>
   angular.module('myApp', [])
   .controller('myController', ['$scope', function($scope) {
   function myController($scope) {
       $scope.add = function(){
           alert("valuea:"+$scope.valuea);
           alert("valueb:"+$scope.valueb);
       } 
   };
}]);

2 个答案:

答案 0 :(得分:1)

您的代码存在某些问题。您的html中没有模块myApp。同样在您的控制器回调中,无需添加控制器名称为function myController() {}的单独函数。

angular.module('myApp', [])
   .controller('myController', ['$scope', function($scope) {
       $scope.add = function(){
           alert("valuea: "+$scope.valuea);
           alert("valueb: "+$scope.valueb);
       } 
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController">
      <p><label>value a : </label><input type="text" ng-model="valuea" name="valuea" id="valuea" /></p>
      <p><label>value b  : </label><input name="valueb" id="valueb" ng-model="valueb"/></p>
      <button type="button" ng-click = "add()"  >Sign In</button>
  </div>
</div>

查看工作提琴-https://jsfiddle.net/otqzk6ua/

答案 1 :(得分:0)

这是答案:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myController">
      <p>
        <label>value a : </label><input type="text" ng-model="valuea" name="valuea" id="valuea" />
      </p>
      <p>
        <label>value b : </label><input name="valueb" id="valueb" ng-model="valueb" />
      </p>

      <button type="button" ng-click="add()">Sign In</button>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
  $scope.add = function() {
    alert("valuea:" + $scope.valuea);
    alert("valueb:" + $scope.valueb);
  }
});
</script>

</body>
</html>